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

NestJS中Swagger嵌套数据结构请求体展示异常求助

NestJS Swagger 嵌套数组DTO 文档展示修复方案

问题场景

使用NestJS开发API并通过Swagger生成接口文档时,CreateWoopDto中的content字段(类型为WoopStatementDto[])在Swagger文档的请求体中未正确展示嵌套数组结构,无法体现数组内元素的字段定义。

原DTO代码如下:

export class CreateWoopDto {
  @ApiProperty()
  @IsUUID()
  user_id: string;

  @ApiProperty()
  @ValidateNested({ each: true })
  @Type(() => WoopStatementDto)
  @IsArray()
  content: WoopStatementDto[];
}


export class WoopStatementDto {
  @ApiProperty()
  @IsString()
  if: string;

  @ApiProperty()
  @IsString()
  then: string;
}

解决方案

问题根源在于@ApiProperty()未明确指定数组的嵌套元素类型,Swagger无法自动推断完整结构。只需修改content字段的@ApiProperty装饰器配置,明确声明数组类型及元素DTO:

export class CreateWoopDto {
  @ApiProperty()
  @IsUUID()
  user_id: string;

  // 修改此处的@ApiProperty配置
  @ApiProperty({ type: [WoopStatementDto] })
  @ValidateNested({ each: true })
  @Type(() => WoopStatementDto)
  @IsArray()
  content: WoopStatementDto[];
}


export class WoopStatementDto {
  @ApiProperty()
  @IsString()
  if: string;

  @ApiProperty()
  @IsString()
  then: string;
}

原理说明

通过@ApiProperty({ type: [WoopStatementDto] }),我们明确告诉Swagger:

  • content是一个数组(通过数组包裹类型的写法[WoopStatementDto])
  • 数组中的每个元素都遵循WoopStatementDto的字段定义

修改后,Swagger文档会正确展示content为数组结构,每个元素包含if和then两个字符串字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:04:59