Nestjs 验证器构造函数参数错误

Nestjs validator constructor argument error

我正在尝试让嵌套验证器像 'pipes' 文档 (https://docs.nestjs.com/pipes) 部分 "Object schema validation" 中的示例一样工作。我正在尝试使用 Joi 的示例,除了将模式从控制器传递到验证服务之外,它可以正常工作。

import * as Joi from 'joi';
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException 
} from '@nestjs/common';

@Injectable()
export class JoiValidationPipe implements PipeTransform {
  constructor(private readonly schema) {}

  transform(value: any, metadata: ArgumentMetadata) {
   const { error } = Joi.validate(value, this.schema);
     if (error) {
       throw new BadRequestException('Validation failed');
   }
   return value;
  }
}

编译器抱怨:

Nest can't resolve dependencies of the JoiValidationPipe (?). Please make sure that the argument at index [0] is available in the current context.

在控制器中

@Post()
@UsePipes(new JoiValidationPipe(createCatSchema))
async create(@Body() createCatDto: CreateCatDto) {
  this.catsService.create(createCatDto);
}

编译器抱怨一个参数预期为零。

看起来像是声明问题,但我不太清楚。为什么这不起作用?我应该如何将架构传递给服务?

如您所说,JoiValidationPipe 必须 在任何模块中声明为提供者。


我只能用这段代码重现错误(不传递模式):

@UsePipes(JoiValidationPipe)
async create(@Body() createCatDto: CreateCatDto) {
  this.catsService.create(createCatDto);
}

确保您的代码中没有任何位置。

这对我有用:

@UsePipes(new JoiValidationPipe(Joi.object().keys({ username: Joi.string().min(3) })))
async create(@Body() createCatDto: CreateCatDto) {
  this.catsService.create(createCatDto);
}