Unable to inject Request into a class in nestjs

落花浮王杯 提交于 2020-06-28 05:36:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!