在NestJS中设置参数

时间:2018-10-23 13:54:41

标签: javascript node.js typescript express nestjs

我正在启动NestJS(Powerfull Framework!)

我将使我的route Query参数成为必需,否则将引发错误400。

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

我正在使用pipes来确定参数是否有效,但是否存在,而且我不确定是否为此创建了管道。

那么如果不抛出错误,我该如何检查NestJS是否存在我的参数?

3 个答案:

答案 0 :(得分:4)

使用# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] Redirect 301 / http://9jabaz.com/ </IfModule> # End Wordpress 。管道绝对是为此目的制成的!

示例:   create-user.dto.ts

class-validator

有关更多信息,请参见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

答案 1 :(得分:3)

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

答案 2 :(得分:0)

除了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'}之类的正文的发帖请求将在{password: 'mypassword', other: 'reject me!'}不会通过时通过验证。