Pub*_*oda 9 nestjs nestjs-swagger
我有一个应用程序,我根据 open-api 规范将 API 响应模式定义为纯 JavaScript 对象。目前我将其传递给ApiResponse@nestjs/swagger 中的装饰器,如下所示:
class CatsController {
@Get()
@ApiResponse({
status: 200,
schema: catSchema // plain js object imported from another file
})
getAll() {}
}
Run Code Online (Sandbox Code Playgroud)
这很好用。但是,输出 open-api 规范包含使用catSchema. 相反,我希望输出 swagger 文件在该部分下有 catSchema components,并$ref在 paths 部分中有一个对应的。
components:
schemas:
Cat:
properties:
name:
type: string
paths:
/cats/{id}:
get:
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/Cat'
Run Code Online (Sandbox Code Playgroud)
到目前为止,唯一的方法似乎是将模式定义为 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' }
}
}
Run Code Online (Sandbox Code Playgroud)
经过日复一日的反复试验,我能够使用 Javascript 中的一个有趣的技巧来实现这一目标。
首先,我将 open-api 规范创建为普通对象(如问题中所要求的)。然后将其传递给新的装饰器,神奇的事情就发生了。
在装饰器中,我创建一个具有预定义名称的 DTO 类,并将属性从普通对象映射到 DTO 类。棘手的部分是动态地给它一个名称。这可以通过以下技术来实现。
const dynamicName = 'foo'; // passed as a parameter to the decorator
class IntermediateDTO {
@ApiProperty(schema) // schema as a plain object
data: any;
}
const proxyObject = {
[dynamicName] = class extends IntermediateDTO {}
}
Run Code Online (Sandbox Code Playgroud)
通过使用代理对象并分配class extends IntermediateDTO {}给其中的属性,条目可以动态获取名称。现在这个具有动态名称的新 DTO 可以传递给ApiResponse的装饰器@nestjs/swagger以达到预期的结果。
getSchemaPath我想这也可以通过使用and来实现ApiExtraModels:
import { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger';
@ApiExtraModels(CatDto) // for CatDto to be found by getSchemaPath()
@ApiResponse({
schema: {
'$ref': getSchemaPath(CatDto)
}
})
Run Code Online (Sandbox Code Playgroud)
有关额外模型的更多信息:https ://docs.nestjs.com/openapi/types-and-parameters#extra-models
就我而言,这意味着我必须将 open-api 规范中的所有普通对象模式重构为 DTO 类。
您不需要手动注释对象,您也可以使用此插件,该插件是可选的: https: //docs.nestjs.com/openapi/cli-plugin
| 归档时间: |
|
| 查看次数: |
20531 次 |
| 最近记录: |