【问题标题】:ValidationPipe doesn't strip given object in NestjsValidationPipe 不会剥离 Nestjs 中的给定对象
【发布时间】:2022-01-16 09:51:06
【问题描述】:

我正在使用 Nestjs 和 Mongoose orm,问题是 ValidationPipe 不会从请求中删除无效道具并将给定(原始)请求发送到我的服务。

这是 ma​​in.ts

async function bootstrap() {
   const app = await NestFactory.create(AppModule, {
      cors: { origin: '*' },
    });

   app.useGlobalPipes(new ValidationPipe(
     {
        transform: true,
        whitelist: true,
     }
   ))

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

这是 update-category.dto

export class UpdateCategoryDto {

 @IsDefined()
 id:string

 @IsDefined()
 title: string;

 @IsDefined()
 url: string;

}

最后是 category.service

async updateCategories(categories: [UpdateCategoryDto]){
   for (let i = 0; i < categories.length ; i++) {
      console.log("given categories",categories);
      await this.categoryModel.updateOne([{ _id: categories[i].id }],categories[i]);
   
   }
} 

这是我的简单控制器

@Controller('categories')
export class CategoryController {

  constructor(private categoryService: CategoryService) {}



  @Put()
  editCategories( @Body() updateCategories: [UpdateCategoryDto]) {
    return this.categoryService.updateCategories(updateCategories);
  }

}

当“给定类别”记录项目时,它们有 _id 哪个前端发送到 api 而我没有在我的 dto 中将该道具列入白名单。为什么我要接收那个道具?我也尝试了“forbidNonWhitelisted”,有趣的是请求没有失败:)) 似乎 useGlobalPipes 对我不起作用

【问题讨论】:

  • 你能把控制器也展示一下吗?
  • @JayMcDoniel 完成。
  • 泛型(哪些是数组)不能被 Typescript 正确反映。这就是为什么 Nest 在您明确需要将数组验证为主体时使用 ParseArrayPipe 的原因
  • @JayMcDoniel 我把控制器改成了这个editCategories( @Body(new ParseArrayPipe()) updateCategories: [UpdateProductCategoryDto]) 没有任何改变

标签: javascript mongoose nestjs


【解决方案1】:

只需使用ParseArrayPipe

更新您的controller.ts

@Put()
editCategories(@Body(new ParseArrayPipe({ items: UpdateCategoryDto, whitelist: true })) updateCategories: UpdateCategoryDto[]) {
  return this.categoryService.updateCategories(updateCategories);
}

确保设置了itemswhitelist

【讨论】:

    猜你喜欢
    • 2021-02-23
    • 2023-03-18
    • 2022-11-17
    • 2021-06-11
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多