NestJS v10中如何为动态键值对DTO配置Swagger ApiProperty
解决NestJS v10中TodoDto Swagger Schema为空的问题
问题原因
TypeScript的索引签名[userId: string]: ProfileDto默认不会被@nestjs/swagger自动解析为Swagger Schema,因此Swagger中显示为空对象{}。
解决方案
需要显式为TodoDto配置Swagger Schema,明确它是一个以字符串为键、ProfileDto为值的对象,同时可自定义示例键。
方法1:使用@ApiSchema装饰器
直接在TodoDto类上添加@ApiSchema装饰器,定义对象结构和示例:
import { ApiSchema } from '@nestjs/swagger'; import { ProfileDto } from './profile.dto'; @ApiSchema({ type: 'object', // 指定值的类型为ProfileDto的Schema引用 additionalProperties: { $ref: '#/components/schemas/ProfileDto' }, // 自定义示例键和对应值 example: { 'user_123': { name: 'Michael', surname: 'Johnson' }, 'user_456': { name: 'Alice', surname: 'Smith' } } }) export class TodoDto { [userId: string]: ProfileDto; }
方法2:结合@ApiExtraModel和@ApiProperty
若需更灵活的配置,先注册ProfileDto为Swagger模型,再在TodoDto中引用:
- 在模块或控制器中注册ProfileDto:
import { ApiExtraModel } from '@nestjs/swagger'; import { ProfileDto } from './profile.dto'; @ApiExtraModel(ProfileDto) export class YourModule {} // 或你的控制器类
- 修改TodoDto定义:
import { ApiProperty } from '@nestjs/swagger'; import { ProfileDto } from './profile.dto'; export class TodoDto { @ApiProperty({ type: 'object', additionalProperties: { $ref: '#/components/schemas/ProfileDto' }, // 支持空字符串键的示例 example: { '': { name: 'Michael', surname: 'Johnson' } } }) [userId: string]: ProfileDto; }
注意事项
- 确保ProfileDto已被Swagger正确识别(要么通过
@ApiExtraModel注册,要么在某个@ApiResponse中被引用),否则$ref无法找到对应Schema。 - 示例中的键可根据业务需求自定义,比如空字符串或实际用户ID格式。
内容的提问来源于stack exchange,提问作者Mike M
相关产品推荐
相关产品推荐

