简体   繁体   English

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

[英]How to make param required in NestJS?

I would like to make my route Query parameter required.我想让我的路由Query参数成为必需参数。 If it is missing I expect it to throw 404 HTTP error.如果它丢失了,我希望它会抛出 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> {
   ...
  }
}

I'm using NestJs pipes to determine if a parameter is valid, but not if it exists And I'm not sure that Pipes are made for that.我正在使用NestJs 管道来确定参数是否有效,但如果它存在则不是,而且我不确定管道是否为此而制作。

So how can I check in NestJS if my param exists if not throw an error?那么,如果我的参数存在,如果不抛出错误,我该如何检查 NestJS?

Use class-validator .使用class-validator Pipes are definitely made for that !管道绝对是为此而制造的!

Example : create-user.dto.ts示例: create-user.dto.ts

import { IsNotEmpty } from 'class-validator';

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

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

And NestJS Pipes & Validation documentation : https://docs.nestjs.com/pipes https://docs.nestjs.com/techniques/validation和 NestJS 管道和验证文档: https : //docs.nestjs.com/pipes https://docs.nestjs.com/techniques/validation

NestJS does not provide a decorator (like @Query ) that detects undefined value in request.query[key] . NestJS 不提供装饰器(如@Query )来检测request.query[key]中的未定义值。

You can write custom decorator for that:您可以为此编写自定义装饰器

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
  }
)

Then use @QueryRequired decorator as you would use @Query :然后像使用@QueryRequired一样使用@Query装饰器:

@Get()
async someMethod(@QueryRequired('requiredParam') requiredParam: string): Promise<any> {
    ...
}

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

In addition to Phi's answer, you can combine the use of class-validator with the following global validation pipe:除了 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,
    }),
  );

I use this in order to only allow parameters defined in the DTO class so that it will throw an error when unknown parameters are sent with the request!我使用它是为了只允许在 DTO 类中定义的参数,以便在请求发送未知参数时会抛出错误!

In Phie's example, a post request with a body like {password: 'mypassword'} will pass the validation when {password: 'mypassword', other: 'reject me!'} won't.在 Phie 的示例中,当{password: 'mypassword', other: 'reject me!'}不会通过验证时,具有类似{password: 'mypassword'}正文的 post 请求将通过验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM