always_bloo
always_bloo

Reputation: 185

How to change query parameters serialization using nestjs/swagger?

Recently I have updated nestjs/swagger package in my project to ^4.0.0. Previously Swagger serialized my query parameters as follows:

/resources?parameter=1,2,3

Now it looks like this:

/resources?parameter=1&parameter=2&parameter=3

DTO object for my query looks like this:

class QueryDTO {
  @ApiProperty({
    required: false,
    type: [Number],
  })
  @IsOptional()
  readonly parameter?: number[];
}

How can I change this behaviour?

Upvotes: 4

Views: 11850

Answers (2)

n3vrax
n3vrax

Reputation: 51

As a workaround, you can remove the @ApiProperty from the DTO and use the @ApiQuery decorator on the controller method which has the style and explode options(just keep the same parameter name as the dto property)

    @Get('resources')
    @ApiQuery({
        name: 'parameter',
        required: false,
        explode: false,
        type: Number,
        isArray: true
    })
    getResources(@Query('parameter') parameter?: number[]) {}

You can still use the DTO object as it is for additional parameters that work the usual way.

Upvotes: 4

Huantao
Huantao

Reputation: 935

I am on nestjs/swagger 4.5.9

I made it work by define the DTO ( notice the format: 'form')

  @IsNotEmpty()
  @ApiProperty({
    type: [Number],
    format: 'form',
  })
  @IsArray()
  @Transform((value: string) => value.split(',').map(item => Number(item)))
  @IsNumber({}, {each: true})
  deviceId: Array<number>;

Upvotes: 8

Related Questions