【问题标题】:Unable to add '[]' to @Query name. Tried multiple ways无法将 \'[]\' 添加到 @Query 名称。尝试了多种方式
【发布时间】:2023-01-28 01:34:17
【问题描述】:

我正在使用 @nestjs/swagger 获取 API 文档。当 swagger 发出请求时,我希望我的 queryParam 是 features[] 而不是 features。 Nest 会自动在路由处理程序和文档中搜索 @Query

SwaggerModule 搜索路由处理程序中的所有@Body()、@Query() 和@Param() 装饰器以生成 API 文档。它还通过利用反射创建相应的模型定义。 来自:https://docs.nestjs.com/openapi/types-and-parameters

因此,如果我的变量名称在代码中是 features,文档会自动选择它。请求失败,因为 features 不是单个元素的数组。如果我尝试使用 @ApiQuery 将参数单独添加到 swagger 文档中,我可以选择将参数命名为 features[] 但它会单独显示,而且我无法删除自动添加的 features 参数。

@Get('/:uuid/configs')
  @ApiOperation({
    summary: 'Get configs for user',
  })

  //manually add param with [] in the name
  @ApiQuery({
    name: 'features[]',
    required: true,
    type: [String],
  })

  async getUserConfigs(
    //automatic pickup from here
    @Query() queryParams: GetUserConfigQueryParamsDto,
  ) {

    return {
      success: true,
    } as ResponseBuilder;
  }

This is how swagger looks with above code

我还尝试按需要将查询名称作为@Query 中的参数传递。

@Get('/:uuid/configs')
  @ApiOperation({
    summary: 'Get configs for user',
  })

  //manually add param with [] in the name
  @ApiQuery({
    name: 'features[]',
    required: true,
    type: [String],
  })

  async getUserConfigs(
    //Added the desired name as a param
    @Query('features[]') queryParams: GetUserConfigQueryParamsDto,
  ) {

    return {
      success: true,
    } as ResponseBuilder;
  }

这肯定会大摇大摆地更改名称。但是当我在这种情况下执行请求时,由于编码原因,[ 转换为%5B%5D。所以请求失败。

我只想要 features[] 而不是两者。但我无法删除@Query 或将[] 添加到变量名。我如何只获得features[]

这是GetUserConfigQueryParamsDtojic:

export class GetUserConfigQueryParamsDto {
  @ApiProperty()
  @IsDefined()
  @IsArray()
  @ArrayNotEmpty()
  features: string[];
}

【问题讨论】:

    标签: swagger nestjs swagger-ui nestjs-swagger


    【解决方案1】:

    在 @ApiProperty() 装饰器的 GetUserConfigQueryParamsDto 类中,上面的功能添加这样的名称 @ApiProperty({ name: 'features[]'})

    【讨论】:

      猜你喜欢
      • 2014-11-09
      • 2018-05-09
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      相关资源
      最近更新 更多