【发布时间】:2021-01-06 17:51:07
【问题描述】:
我有一个应用程序,我根据 open-api 规范将 API 响应模式定义为纯 javascript 对象。目前我将其传递给@nestjs/swagger 中的ApiResponse 装饰器,如下所示:
class CatsController {
@Get()
@ApiResponse({
status: 200,
schema: catSchema // plain js object imported from another file
})
getAll() {}
}
这很好用。但是,输出的 open-api 规范包含每个使用 catSchema 的端点的详细架构。 相反,我希望输出 swagger 文件在 components 部分下具有 catSchema,并在路径部分中具有相应的 $ref。
components:
schemas:
Cat:
properties:
name:
type: string
paths:
/cats/{id}:
get:
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/Cat'
到目前为止,似乎唯一的方法是将架构定义为 DTO 类并为每个类属性使用 ApiProperty 装饰器。就我而言,这意味着我必须将 open-api 规范中的所有普通对象模式重构为 DTO 类。
有没有办法将原始模式提供给库并获得预期的结果?
// instead of this:
class CatDto {
@ApiProperty()
name: string;
}
// I want to do:
const catSchema = {
type: 'object',
properties: {
name: { type: 'string' }
}
}
【问题讨论】:
-
简而言之,不,这背后的原因是:
@ApiProperty是 NestJs 中 swagger 理解架构的标签,在内联架构设计中不支持。你能更详细地解释一下你想如何传递模式吗? -
感谢@TanmoyBhattacharjee 的回复。我想将内联模式直接传递给
@ApiResponse。它工作得很好,除了它不做$ref模式。输出包含直接在响应部分下的架构。这有意义吗?
标签: nestjs nestjs-swagger