问题
The class I want to inject the request into looks as follows:
@ValidatorConstraint({ name: 'isUniqueEntryTitle', async: true })
@Injectable({ scope: Scope.REQUEST })
export class IsUniqueEntryTitle implements ValidatorConstraintInterface {
constructor(
private readonly userService: UserService,
@Inject(REQUEST) private request: Request,
) {}
public async validate(val: any, args: ValidationArguments): Promise<boolean> {
console.log('Request', this.request);
return true;
}
public defaultMessage(args: ValidationArguments): string {
return `Entry with such title already exists in this folder`;
}
}
The corresponding method on the controller looks like this:
@Post()
public async createEntry(
@Body() createEntryBodyDto: CreateEntryBodyDto,
@Headers('authorization') authHeader: string): Promise<void> {}
}
And finally the CreateEntryBodyDto
class:
export class CreateEntryBodyDto {
@ApiProperty()
@IsNumberString()
@IsOptional()
id?: number;
@ApiProperty()
@IsString()
@Validate(IsUniqueEntryTitle)
title: string;
@ApiProperty()
@IsString()
body: string;
@ApiProperty()
@IsDateString()
@IsOptional()
startDate?: string;
@ApiProperty()
@IsDateString()
@IsOptional()
finishDate?: string;
}
What I get is this.request
turns out to be undefined. Why would that happen?
来源:https://stackoverflow.com/questions/62522438/unable-to-inject-request-into-a-class-in-nestjs