简体   繁体   中英

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.

This is 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

export class UpdateCategoryDto {

 @IsDefined()
 id:string

 @IsDefined()
 title: string;

 @IsDefined()
 url: string;

}

And finally this is 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('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. why I'm receaving that prop?? I also tried `forbidNonWhitelisted' and interestingly request didn't fail:)) seems useGlobalPipes doesn't work for me

Just use ParseArrayPipe .

Just update your 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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