Home > Blockchain >  NestJs: DTO showing all query parameters
NestJs: DTO showing all query parameters

Time:06-15

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.

CodePudding user response:

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

  • Related