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 class CreateDataParams {
@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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…