我试图在我的NestJS应用程序中使用swagger,但我无法定义用于additionalProperties类型的自定义类。
我有一个自定义类:
@ApiExtraModels(Entity)
export class Entity {
@ApiProperty({description:"Map of the entities"}) entityID: string;
}
在此之后,我检查了模式路径(应该使用ApiExtraModels装饰器定义)是否已定义-控制台日志...
console.log("getSchemaPath", getSchemaPath('Entity'));
...indeed的输出为:
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>;
}
但是给定对象的swagger上的输出是:
{
"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时,我做错了什么?
发布于 2020-07-16 13:56:43
正如问题#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 {
...
}
https://stackoverflow.com/questions/61351164
复制相似问题