Skip to content Skip to sidebar Skip to footer

How To Apply Both Validationpipe() And Parseintpipe() To Params?

I'm trying to apply both the ValidationPipe() and ParseIntPipe() to the params in my NestJs controller. The intention is to apply ParseIntPipe() only on @Param('id') but Validation

Solution 1:

If you apply the ParseIntPipe to the id param, it will only transform id but not the property id of params, here it will stay a string.

Instead, you can use class-transformer to transform your param to a number:

import { Transform } from'class-transformer';
export classCreateDataParams {
  @Transform(id => parseInt(id), {toClassOnly: true})id: number;
}

Then you use the ValidationPipe with the option transform: true:

@Post(':id')
@UsePipes(new ValidationPipe({transform: true}))
async create(
    @Param() params: CreateDataParams,
    @Body() createDto: CreateDto
) {
    // params.id
}

Note though, that this is unsafe because e.g. parseInt('5abc010') is 5. So you might want to do additional checks in your transformation function.

Post a Comment for "How To Apply Both Validationpipe() And Parseintpipe() To Params?"