2

I have 2 routes, one is POST, it uses @ApiBody decorator and works correctly, the other one is GET, and I don't know what decorators should I use for generating the correct api.

class ImagesRequestDto {
  @ApiProperty({ type: String })
  @IsOptional()
  srch?: string

  @ApiProperty({ type: Number })
  @IsOptional()
  @Min(0)
  offset?: number

  @ApiProperty({ type: Number })
  @IsOptional()
  @Min(0)
  @Max(1000)
  limit?: number
}

// This one works:
@ApiBody({ type: ImagesRequestDto })
@ApiResponse({ status: 200, type: ImagesResponseDto })
@Post('list-post')
async listPost(@Req() request: Request, @Body() filter: ImagesRequestDto): Promise<ImagesResponseDto> {
  const [images, count] = await this.imagesService.getUserImages(filter)
  request.res.status(200)
  return { images, count }
}

// This one generates incorrect openapi:
@ApiQuery(ImagesRequestDto)
// Or @ApiQuery({ type: ImagesRequestDto, name: 'filter' })
@ApiResponse({ type: ImagesResponseDto })
@Get('list-get')
async listGet(@Query() filter: ImagesRequestDto): Promise<ImagesResponseDto> {
  const [images, count] = await this.imagesService.getUserImages(filter)
  return { images, count } 
}

I generate openapi.json with @nestjs/swagger and then run nswag to generate api.ts file for the front-end. The result is:

listPost(body: ImagesRequestDto, cancelToken?: CancelToken | undefined): Promise<ImagesResponseDto> {
   ...axios request post...
}

listGet(srch: string, offset: number, limit: number, imagesRequestDto: any , cancelToken?: CancelToken | undefined): Promise<ImagesResponseDto> {
   ...axios request get...
}

So it has imagesRequestDto: any (why?) and some destructured arguments from imagesRequestDto. I want listGet to accept the same arguments as listPost - there should 2 arguments, the first one is query: ImagesRequestDto, the second is cancelToken. That is much more convenient (especially with many filtering arguments) since this case it can be used by

const images = await imagesClient.listGet(ImagesRequestDto.fromJS({..specify only required arguments..}))

instead of

const images = await imagesClient.listGet(srch, first, second, third, ..., offset, limit)

Is it possible to achieve or is there any limitation for get requests in openapi?

Kasheftin
  • 7,509
  • 11
  • 41
  • 68

0 Answers0