首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NestJS Swagger -不使用ApiExtraModels装饰器的自定义类的additionalProperties的定义

NestJS Swagger -不使用ApiExtraModels装饰器的自定义类的additionalProperties的定义
EN

Stack Overflow用户
提问于 2020-04-22 03:02:00
回答 1查看 1.5K关注 0票数 2

我试图在我的NestJS应用程序中使用swagger,但我无法定义用于additionalProperties类型的自定义类。

我有一个自定义类:

代码语言:javascript
运行
复制
@ApiExtraModels(Entity) 
export class Entity {  
     @ApiProperty({description:"Map of the entities"}) entityID: string; 
}

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

代码语言:javascript
运行
复制
console.log("getSchemaPath", getSchemaPath('Entity'));

...indeed的输出为:

代码语言:javascript
运行
复制
getSchemaPath #/components/schemas/Entity

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

代码语言:javascript
运行
复制
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>;
}

但是给定对象的swagger上的输出是:

代码语言:javascript
运行
复制
{
   "levelName": "string",
   "levelEntities": {}
} 

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

代码语言:javascript
运行
复制
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;
}

则对象的夸张是所需的:

代码语言:javascript
运行
复制
{
  "levelName": "string",
  "levelEntities": {
    "additionalProp1": {
      "entityID": "string"
    },
    "additionalProp2": {
      "entityID": "string"
    },
    "additionalProp3": {
      "entityID": "string"
    }
  }
}

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

EN

回答 1

Stack Overflow用户

发布于 2020-07-16 13:56:43

正如问题#738中所提到的,ApiExtraModels将在方法之上使用,而不是在模型类之上使用。

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

代码语言:javascript
运行
复制
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中定义额外的模型

代码语言:javascript
运行
复制
SwaggerModule.createDocument(app, config, {
   extraModels: [.......]
});

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

代码语言:javascript
运行
复制
@ApiExtraModels(EntityA, EntityB)
export class EntityLevel {
   ...
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61351164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档