Search code examples
javascriptnode.jsswaggernestjsdto

NestJs: DTO showing all query parameters


I'm trying to use 2 separate dto for query parameters in NestJs. However, on printing both dtos are showing same properties. Is there any way to separate them.

// dto code

export class PageDto {
  @Type(() => Number)
  @IsInt()
  page: number;

  @Type(() => Number)
  @IsInt()
  limit: number;
}

export class MyDto {
  @ApiPropertyOptional()
  @IsString()
  @IsOptional()
  status: string;

  @ApiPropertyOptional()
  @IsString()
  @IsOptional()
  source: string;
}

Api request:

GET url?page=1&limit=10&status='active'&source='firebase'

controller:

@Get()
  async get(
    @Query() myDto: MyDto,
    @Query() pageDto: PageDto,
  ) {
     console.log({pageDto}, {myDto});
  } 

Console statement prints:

{
   pageDto: {
    page: 1,
    limit: 10,
    status: 'active',
    source: 'firebase'
   }
}

{
   myDto: {
    page: 1,
    limit: 10,
    status: 'active',
    source: 'firebase'
   }
}

Required:

{
   pageDto: {
    page: 1,
    limit: 10
   }
}

{
   myDto: {
    status: 'active',
    source: 'firebase'
   }
}

Ideally, pageDto and myDto should show their respective properties.


Solution

  • You'll need to set whitelist: true in your ValidationPipe options to tell class-transformer and class-validator to strip out the properties that don't exist on the DTO.

    Reference to the docs