【发布时间】: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 时我做错了什么?
【问题讨论】: