How to use ParseIntPipe and Dto together?

Viewed 2467

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;
}
2 Answers

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()
  @Transform(val => Number.parseInt(val))
  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.

The updated syntax for @Transorm decorator.

import { Transform } from 'class-transformer';

export class Photo {
  id: number;

  @Transform(({ value }) => parseInt(value))
  index: number;
}
Related