nestjsdto

How can I use ParseIntPipe and Dto together?


From query I get limit param. How to transform into number and check by Dto ?

  @Get('currency/:type')
  getCurrency(
    @Param() params: CurrencyTypeDto,
    @Query('limit', ParseIntPipe) limit: number,
    @Query() query: PaginationLimitDto
  ) {

PaginationLimitDto

export class PaginationLimitDto {
    @IsOptional()
    @IsInt()
    limit: number;
}

Solution

  • Query and URL parameters always come in as an object of strings, just howthe underlying engines handle them. What you can do, with your DTO, is add the @Transform() decorator and do something like

    export class PaginationLimitDto {
      @IsOptional()
      @IsInt()
      // pre 0.3.2 syntax
      @Transform(val => Number.parseInt(val))
      // after 0.3.2 syntax*
      @Transform({ value } => Number.parseInt(value))
      limit: number;
    }
    

    Then you only need @Query() query: PaginationLimitDto in your method handler. Nest's ValidationPipe will take care of calling class-transformer and class-validator for you.

    *See changelog on Github