如何在 NestJS 中使参数成为必需的?

How to make param required in NestJS?

我想让我的路由 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 是否存在我的参数?

有一种简单的方法可以验证您的参数,https://docs.nestjs.com/techniques/validation

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

示例: 创建-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

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

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

NestJS 不提供检测未定义的装饰器(如@Queryrequest.query[key].

中的值

你可以这样写 custom decorator:

import { createParamDecorator, ExecutionContext, BadRequestException } from '@nestjs/common'

export const QueryRequired = createParamDecorator(
  (key: string, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest()

    const value = request.query[key]

    if (value === undefined) {
      throw new BadRequestException(`Missing required query param: '${key}'`)
    }

    return value
  }
)

然后像使用 @Query:

一样使用 @QueryRequired 装饰器
@Get()
async someMethod(@QueryRequired('requiredParam') requiredParam: string): Promise<any> {
    ...
}