Skip to content
Advertisement

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

Advertisement

Answer

Just use ParseArrayPipe.

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement