代码之家  ›  专栏  ›  技术社区  ›  infodev

使NestJS中需要参数

  •  2
  • infodev  · 技术社区  · 7 年前

    Query 需要参数。

    @Controller('')
    export class AppController {
      constructor() {}
      @Get('/businessdata/messages')
      public async getAllMessages(
        @Query('startDate', ValidateDate) startDate: string,
        @Query('endDate', ValidateDate) endDate: string,
      ): Promise<string> {
       ...
      }
    }
    

    我在用 NestJs pipes 以确定参数是否有效,但不确定它是否存在,而且我不确定是否为此制作了管道。

    如果我的参数存在,如果不抛出错误,我怎么签入NestJS呢?

    2 回复  |  直到 5 年前
        1
  •  9
  •   Phie    7 年前

    使用 class-validator

    例子: 创建-user.dto.ts

    import { IsNotEmpty } from 'class-validator';
    
    export class CreateUserDto {
       @IsNotEmpty()
       password: string;
    }
    

    类验证程序 文档: https://github.com/typestack/class-validator

    和NestJS管道;验证文件: https://docs.nestjs.com/pipes https://docs.nestjs.com/techniques/validation

        2
  •  4
  •   jkchao    7 年前

    有一个简单的方法来验证你的参数, https://docs.nestjs.com/techniques/validation

        3
  •  0
  •   Philou    7 年前

    除了Phi的答案,还可以结合使用 class-validator 使用以下全局验证管道:

    app.useGlobalPipes(
        new ValidationPipe({
          /*
                If set to true, instead of stripping non-whitelisted 
                properties validator will throw an exception.
          */
          forbidNonWhitelisted: true,
          /*
                If set to true, validator will strip validated (returned) 
                object of any properties that do not use any validation decorators.
          */
          whitelist: true,
        }),
      );
    

    我这样做是为了只允许DTO类中定义的参数,这样当请求中发送未知参数时,它就会抛出一个错误!

    {password: 'mypassword'} 将在以下时间通过验证 {password: 'mypassword', other: 'reject me!'} 不会。