简体   繁体   中英

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?

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>;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM