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 ValidationPipe()
for all params in CreateDataParams
and Body DTO.
However, I can't seem to apply both pipes the way I wanted. Here's what I have:
@Post(':id')
@UsePipes(new ValidationPipe())
async create(
@Param('id', new ParseIntPipe()) id: number, //this doesn't work
@Param() params: CreateDataParams,
@Body() createDto: CreateDto
) {
// params.id
}
I have tried having another @Param('id')
to apply the ParseIntPipe()
transformer but this doesn't work.
How can I apply both ValidationPipe()
and ParseIntPipe()
to the params?
If you apply the
ParseIntPipe
to theid
param, it will only transformid
but not the propertyid
ofparams
, here it will stay astring
.Instead, you can use
class-transformer
to transform your param to anumber
:Then you use the
ValidationPipe
with the optiontransform: true
:Note though, that this is unsafe because e.g.
parseInt('5abc010')
is5
. So you might want to do additional checks in your transformation function.