【问题标题】:NestJS Swagger - Definition of additionalProperties of a custom class not working with ApiExtraModels decoratorNestJS Swagger - 自定义类的附加属性的定义不与 ApiExtraModels 装饰器一起使用
【发布时间】:2020-08-04 15:35:44
【问题描述】:

我正在尝试在我的 NestJS 应用程序中使用 swagger,但我无法定义自定义类以用于附加属性类型。

我有一个自定义类:

@ApiExtraModels(Entity) 
export class Entity {  
     @ApiProperty({description:"Map of the entities"}) entityID: string; 
}

在此之后,我检查了架构路径(应使用 ApiExtraModels 装饰器定义)是否已定义 - 控制台日志...

console.log("getSchemaPath", getSchemaPath('Entity'));

...确实有输出:

getSchemaPath #/components/schemas/Entity

在这段代码之后,我尝试将此模式用作附加属性的类型:

export class EntityLevel {
  @ApiProperty({description:"Generic name of the entities in the current level"})
  levelName: string;

  @ApiProperty({
    description:"Map object of the Entities - [GUID: string]: Entity",
    type: 'object',
    additionalProperties: {$ref: getSchemaPath('Entity')}
  })
  levelEntities: Map<string, Entity>;
}

但是给定对象的大摇大摆的输出是:

{
   "levelName": "string",
   "levelEntities": {}
} 

我目前的解决方法是删除 @ApiExtraModels 装饰器并将 Entity 类型的虚拟属性添加到另一个类,然后它可以正常工作(当然,我不想拥有一个虚拟属性):

export class RandomClass {
  id: String;

  @ApiPropertyOptional({
    description: "This is a dummy entity added as a workaround for not being able to include Entity type otherwise",
    type: Entity
  })
  dummyEntity?: Entity;
}

那么对对象的招摇就是如愿:

{
  "levelName": "string",
  "levelEntities": {
    "additionalProp1": {
      "entityID": "string"
    },
    "additionalProp2": {
      "entityID": "string"
    },
    "additionalProp3": {
      "entityID": "string"
    }
  }
}

尝试使用 @ApiExtraModels 装饰器定义 ExtraModel 时我做错了什么?

【问题讨论】:

    标签: swagger nestjs openapi


    【解决方案1】:

    如问题#738 中所述,ApiExtraModels 将用于方法之上,而不是模型类之上。

    因此您的解决方案应该是:

    export class Entity {  
         @ApiProperty({description:"Map of the entities"}) entityID: string; 
    }
    
    @ApiExtraModels(Entity)
    export class EntityLevel {
      @ApiProperty({description:"Generic name of the entities in the current level"})
      levelName: string;
    
      @ApiProperty({
        description:"Map object of the Entities - [GUID: string]: Entity",
        type: 'object',
        additionalProperties: {$ref: getSchemaPath(Entity)}
      })
      levelEntities: Map<string, Entity>;
    }
    
    

    另一种方法是在 main.ts 处定义额外的模型:

    SwaggerModule.createDocument(app, config, {
       extraModels: [.......]
    });
    

    就我而言,我需要将额外的模型放入 { oneOf: [] }。这可以通过在 ApiExtraModels 注释中列出额外的模型来轻松解决,例如:

    @ApiExtraModels(EntityA, EntityB)
    export class EntityLevel {
       ...
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      • 2013-02-06
      • 2011-07-11
      • 2018-10-25
      相关资源
      最近更新 更多