最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to apply both ValidationPipe() and ParseIntPipe() to params? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Apr 2, 2019 at 17:52 Kim Kern 60.4k20 gold badges216 silver badges212 bronze badges asked Apr 2, 2019 at 17:26 CarvenCarven 15.6k30 gold badges124 silver badges183 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 20

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)

  1. 暂无评论