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

NestJS中嵌套超1层时Swagger不应用ApiProperty的问题

问题:多层嵌套字段中@ApiProperty的date-time格式不生效

我尝试在类的嵌套字段上使用@ApiProperty({ format: "date-time" })注解,第一层及嵌套一层的字段上该注解可正常生效,但嵌套超过一层时,Swagger文档的请求示例中格式不再生效。

示例代码:

class testDto {
  @ApiProperty({ format: "date-time" })
  date: string //This works: "2022-09-29T15:28:15.931Z"

  @Type(() => Foo)
  @ValidateNested()
  foo: Foo;
}

class Foo {
  @ApiProperty({ format: "date-time" })
  date: string //This works: "2022-09-29T15:28:15.931Z"

  @Type(() => Bar)
  @ValidateNested()
  bar: Bar;
}

class Bar {
  @ApiProperty({ format: "date-time" })
  date: string //This does not work: "string"
}

生成的Swagger示例如下:

"date": "2022-09-29T15:28:15.931Z",
"foo": {
    "date": "2022-09-29T15:28:15.931Z",
    "bar": {
      "date": "string"
    }
  }

请问如何让ApiProperty对多层嵌套字段生效?


解决方案

可以通过以下几种方式解决多层嵌套字段的@ApiProperty格式失效问题:

  • 给最深层的DTO类添加Swagger识别注解:在Bar类上添加@ApiSchema()(@nestjs/swagger v7+版本)或@ApiModel()(旧版本),让Swagger明确识别该类的元数据:

    import { ApiSchema } from '@nestjs/swagger';
    
    @ApiSchema()
    class Bar {
      @ApiProperty({ format: "date-time" })
      date: string;
    }
    
  • 在父类嵌套字段上显式指定@ApiProperty的类型:在Foo类的bar字段上,配合@Type和@ValidateNested,给@ApiProperty添加type配置:

    class Foo {
      @ApiProperty({ format: "date-time" })
      date: string;
    
      @ApiProperty({ type: () => Bar })
      @Type(() => Bar)
      @ValidateNested()
      bar: Bar;
    }
    
  • 确保Swagger文档生成时包含所有DTO类:如果使用DocumentBuilder手动构建文档,要在addModels()中包含Bar类;如果使用autoSchemaFile选项,确保所有DTO类都能被框架自动扫描到。

内容的提问来源于stack exchange,提问作者Jorge Rodriguez RV

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:45:29