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
JavaScript
x
16
16
1
async function bootstrap() {
2
const app = await NestFactory.create(AppModule, {
3
cors: { origin: '*' },
4
});
5
6
app.useGlobalPipes(new ValidationPipe(
7
{
8
transform: true,
9
whitelist: true,
10
}
11
))
12
13
await app.listen(3002);
14
}
15
bootstrap();
16
and this is update-category.dto
JavaScript
1
13
13
1
export class UpdateCategoryDto {
2
3
@IsDefined()
4
id:string
5
6
@IsDefined()
7
title: string;
8
9
@IsDefined()
10
url: string;
11
12
}
13
And finally this is category.service
JavaScript
1
8
1
async updateCategories(categories: [UpdateCategoryDto]){
2
for (let i = 0; i < categories.length ; i++) {
3
console.log("given categories",categories);
4
await this.categoryModel.updateOne([{ _id: categories[i].id }],categories[i]);
5
6
}
7
}
8
Here is my simple controller
JavaScript
1
14
14
1
@Controller('categories')
2
export class CategoryController {
3
4
constructor(private categoryService: CategoryService) {}
5
6
7
8
@Put()
9
editCategories( @Body() updateCategories: [UpdateCategoryDto]) {
10
return this.categoryService.updateCategories(updateCategories);
11
}
12
13
}
14
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
:
JavaScript
1
5
1
@Put()
2
editCategories(@Body(new ParseArrayPipe({ items: UpdateCategoryDto, whitelist: true })) updateCategories: UpdateCategoryDto[]) {
3
return this.categoryService.updateCategories(updateCategories);
4
}
5
Ensure to have items
and whitelist
set.