How to apply both ValidationPipe() and ParseIntPipe() to params?

后端 未结 1 518
时光说笑
时光说笑 2020-12-03 22:38

I\'m trying to apply both the ValidationPipe() and ParseIntPipe() to the params in my NestJs controller.

The intention is to apply Pa

相关标签:
1条回答
  • 2020-12-03 22:59

    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.

    0 讨论(0)
提交回复
热议问题