简体   繁体   English

ValidationPipe 不会剥离 Nestjs 中给定的 object

[英]ValidationPipe doesn't strip given object in Nestjs

I'm using Nestjs and Mongoose orm the problem is ValidationPipe doesn't delete invalid props from request and send given(raw) request to my service.我正在使用 Nestjs 和 Mongoose orm 问题是 ValidationPipe 不会从请求中删除无效道具并将给定(原始)请求发送到我的服务。

This is main.ts这是main.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();

and this is update-category.dto这是update-category.dto

export class UpdateCategoryDto {

 @IsDefined()
 id:string

 @IsDefined()
 title: string;

 @IsDefined()
 url: string;

}

And finally this is category.service最后是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]);
   
   }
} 

Here is my simple controller这是我的简单 controller

@Controller('categories')
export class CategoryController {

  constructor(private categoryService: CategoryService) {}



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

}

when "given categories" logs items, they have _id which frontend sent to api while I didn't whitelisted that props in my dto.当“给定类别”记录项目时,他们有 _id 哪个前端发送到 api 而我没有在我的 dto 中将该道具列入白名单。 why I'm receaving that prop??为什么我要接收那个道具? I also tried `forbidNonWhitelisted' and interestingly request didn't fail:)) seems useGlobalPipes doesn't work for me我还尝试了“forbidNonWhitelisted”,有趣的是请求没有失败:)) 似乎 useGlobalPipes 对我不起作用

Just use ParseArrayPipe .只需使用ParseArrayPipe

Just update your controller.ts :只需更新您的controller.ts

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

Ensure to have items and whitelist set.确保设置了itemswhitelist

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

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