【问题标题】:How to make param required in NestJS?如何在 NestJS 中设置参数?
【发布时间】:2019-03-27 19:09:59
【问题描述】:

我想让我的路由 Query 参数是必需的。 如果它丢失,我希望它会抛出 404 HTTP 错误。

@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?

【问题讨论】:

  • 您找到解决方案了吗?在框架内似乎是不可能的。看起来你必须编写一个自定义管道才能做到这一点?
  • 是的,我终于有一个管道可以检查它是否为空
  • 你能提供你的解决方案来检查缺少的参数吗?

标签: javascript node.js typescript nestjs


【解决方案1】:

使用class-validator。管道绝对是为此而制造的!

示例: create-user.dto.ts

import { IsNotEmpty } from 'class-validator';

export class CreateUserDto {
   @IsNotEmpty()
   password: string;
}

有关更多信息,请参阅class-validator 文档: https://github.com/typestack/class-validator

以及 NestJS 管道和验证文档: https://docs.nestjs.com/pipes https://docs.nestjs.com/techniques/validation

【讨论】:

  • 你能用这种方法处理@Query 参数吗?这些只是字符串。 @Get() getName( @Query name: string) { return name}
  • 如果不提供密码值,您现在将收到 500 错误,那么我们该如何处理这种情况?
  • @IsNotEmpty() 装饰器用于检查值是否为空或 null,但他不检查缺少的参数
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    除了 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 类中定义的参数,这样当请求发送未知参数时它会抛出错误!

    在 Phie 的示例中,正文为 {password: 'mypassword'} 的 post 请求将通过验证,而 {password: 'mypassword', other: 'reject me!'} 则不会。

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 2020-10-31
      • 2021-05-26
      • 2019-09-28
      • 2021-09-03
      • 2020-12-17
      • 2021-10-18
      • 2021-09-01
      • 1970-01-01
      相关资源
      最近更新 更多