【问题标题】:Now to enable validators DTO in NEST JS现在在 NEST JS 中启用验证器 DTO
【发布时间】:2020-07-30 09:04:54
【问题描述】:

我是 NEST JS 的新手,现在我尝试在 DTO'S 中包含一些验证器 看起来像:


// /blog-backend/src/blog/dto/create-post.dto.ts
import { IsEmail, IsNotEmpty, IsDefined } from 'class-validator';
export class CreatePostDTO {
  @IsDefined()
  @IsNotEmpty()
  title: string;
  @IsDefined()
  @IsNotEmpty()
  description: string;
  @IsDefined()
  @IsNotEmpty()
  body: string;
  @IsEmail()
  @IsNotEmpty()
  author: string;
  @IsDefined()
  @IsNotEmpty()
  datePosted: string;
}

但是当我执行 post 服务时:

{
    "title":"juanita"
}

它的回报很好! 但是验证器应该正确显示和错误吗?

我的帖子管理员

@Post('/post')
  async addPost(@Res() res, @Body() createPostDTO: CreatePostDTO) {
    console.log(createPostDTO)
    const newPost = await this.blogService.addPost(createPostDTO);
    return res.status(HttpStatus.OK).json({
      message: 'Post has been submitted successfully!',
      post: newPost,
    });
  }

我的 main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  await app.listen(5000);
}
bootstrap();

【问题讨论】:

    标签: node.js typescript nestjs


    【解决方案1】:

    您也可以像这样在app.module.ts 文件中注册全局管道:

    providers: [
        {
          provide: APP_PIPE,
          useValue: new ValidationPipe({
            // validation options
            whitelist: true,
          }),
        },
      ],
    

    【讨论】:

      【解决方案2】:

      为了通过传入的 dto 验证请求,您可以使用 NestJS 提供的 @UsePipes() 装饰器。这个装饰器可以全局应用(对于整个项目),在各个端点上。这就是 NestJS 文档所说的 -

      管道,类似于异常过滤器,可以是方法范围的、控制器范围的或全局范围的。此外,管道可以是参数范围的。在下面的示例中,我们将直接将管道实例绑定到路由参数 @Body() 装饰器。

      因此,将它用于您的 POST 端点将有助于验证请求。 希望这会有所帮助。

      【讨论】:

        【解决方案3】:

        让我们在应用程序级别绑定ValidationPipe,从而确保所有端点都受到保护,不会收到不正确的数据。 Nestjs document

        为您的应用启用ValidationPipe

        main.ts

        import { NestFactory } from '@nestjs/core';
        import { AppModule } from './app.module';
        import { ValidationPipe } from '@nestjs/common'; // import built-in ValidationPipe
        
        async function bootstrap() {
          const app = await NestFactory.create(AppModule);
          app.useGlobalPipes(new ValidationPipe()); // enable ValidationPipe`
          await app.listen(5000);
        }
        bootstrap();
        

        【讨论】:

          猜你喜欢
          • 2023-03-25
          • 2013-02-22
          • 2021-05-08
          • 2021-03-08
          • 1970-01-01
          • 2022-12-30
          • 1970-01-01
          • 1970-01-01
          • 2020-01-06
          相关资源
          最近更新 更多