You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在NestJS中配置Swagger:定义字符串到自定义对象数组的映射

问题:NestJS中配置Swagger字符串键映射自定义对象数组的字典类型

需求是返回一个字符串键映射到自定义对象数组的字典结构,键名不确定,值为固定类型的数组,示例数据如下:

{
  "1": [CustomObjectType, CustomObjectType],
  "5": [CustomObjectType]
}

之前尝试的Swagger配置和NestJS写法都没正确识别数组类型,以下是正确解决方案:


一、Swagger规范的正确配置

你之前的错误是误用了isArray字段,Swagger中定义对象的额外属性为数组时,需要将additionalProperties声明为array类型,并通过items关联目标Schema:

components:
  schemas:
    CustomMap:
      type: object
      additionalProperties:
        type: array
        items:
          $ref: '#/components/schemas/CustomObjectType'
    CustomObjectType:
      type: object
      properties:
        # 这里定义CustomObjectType的字段,比如:
        id:
          type: number
        name:
          type: string

二、NestJS中的两种实现方式

方式1:通过DTO类配合Swagger装饰器

直接用索引签名的DTO类,配合@ApiExtraModels和@ApiProperty配置:

import { ApiExtraModels, ApiProperty, getSchemaPath } from '@nestjs/swagger';
import { CustomObjectType } from './your-path';

@ApiExtraModels(CustomObjectType)
export class CustomMapDTO {
  @ApiProperty({
    type: 'array',
    items: {
      $ref: getSchemaPath(CustomObjectType),
    },
  })
  [key: string]: CustomObjectType[];
}

然后在接口的@ApiResponse中直接引用这个DTO:

@ApiResponse({
  status: 200,
  type: CustomMapDTO,
})
@Get()
getCustomMap(): CustomMapDTO {
  // 业务逻辑
}

方式2:直接在@ApiResponse中配置schema

修正你之前的写法,在additionalProperties里明确声明数组类型并指定元素Schema:

import { ApiResponse, getSchemaPath } from '@nestjs/swagger';
import { CustomObjectType } from './your-path';

@ApiResponse({
  status: 200,
  schema: {
    type: 'object',
    additionalProperties: {
      type: 'array',
      items: {
        $ref: getSchemaPath(CustomObjectType),
      },
    },
  },
})
@Get()
getCustomMap(): Record<string, CustomObjectType[]> {
  // 业务逻辑
}

内容的提问来源于stack exchange,提问作者lia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:45:25