将 @ApiQuery 与 nestJS 和 swagger 一起使用时,有没有办法声明默认值?

Is there a way to declare a default value when using @ApiQuery with nestJS and swagger?

编辑:根据建议使用 DTO 的评论找到了解决方案。答案详见底部

NestJS 网站上有使用@ApiBody() 时[声明默认值][1] 的文档,有没有办法使用@ApiQuery() 来做到这一点? (即在文档中显示查询具有默认值)

例如,如果我有分页查询并希望默认为第 1 页,每页 5 个条目:

  @Get()
  @ApiQuery({name: 'page', default: 1, type: Number})
  @ApiQuery({name: 'limit', default: 5, type: Number})
  async getDocuments(
    @Query('page') page: Number = 1, 
    @Query('limit') limit: Number = 5
  ){
    return this.documentsService.getDocuments(page, limit);
  }

按照评论中的建议使用 DTO:

//dto.ts
export class PageDTO {
  @ApiProperty({default: 1, required: false})
  page: Number
}
export class LimitDTO {
  @ApiProperty({default: 5, required: false})
  limit: Number
}
//documents.controller.ts
...
  @Get()
  @ApiQuery({name: 'page', default: 1, type: PageDTO})
  @ApiQuery({name: 'limit', default: 5, type: LimitDTO})
  async getDocuments(
    @Query('page') page = 1, 
    @Query('limit') limit = 5
  ){
    return this.documentsService.getDocuments(page, limit);
  }

结果: *打错字了,这里默认是 0 但应该是 1

此外,单个 DTO 可用于多个查询参数。如果多个函数使用相同的参数,这将特别有用:

//dto.ts
export class PaginationDTO {
  @ApiProperty({default: 1, required: false})
  page: Number
  @ApiProperty({default: 5, required: false})
  limit: Number
}

//documents.controller.ts
...
  @Get()
  @ApiQuery({type: PaginationDTO})
  async getDocuments(
    @Query('page') page = 1, 
    @Query('limit') limit = 5 
  ){
    return this.documentsService.getDocuments(page, limit);
  }

另请注意我的工作示例中省略了类型声明——这是因为如果声明了类型,swagger 会产生重复的参数

  @Get()
  @ApiQuery({name: 'page', type: Number})
  @ApiQuery({name: 'limit', type: Number})
  async getDocuments(
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: Number = 1, 
    @Query('limit', new DefaultValuePipe(5), ParseIntPipe) limit: Number = 5
  ){
    return this.documentsService.getDocuments(page, limit);
  }