swagger - NestJs-Swagger - 是否可以在 NestExpressApplication 中列出所有 Swagger 文档?
问题描述
我将NestJs与SwaggerModule一起使用,我想在应用程序初始化后列出所有文档。
就像是:
[
{
title: 'Admin',
description: 'Admin endpoints',
version: '1.2.3',
url: 'admin/123/'
},
{
title: 'Resources',
description: 'Resources endpoints',
version: '1.2.5',
url: 'admin/125/'
}
]
是否有我可以访问的具有这些文档信息的对象,还是我必须自己创建它?
解决方案
我刚刚浏览了NestJS
文档,似乎无法在运行时添加提供程序。但这并非不可能。
- 创建服务
SwaggerDocumentService
@Injectable()
export class SwaggerDocumentService {
private _swaggerDocuments: Array<Omit<OpenAPIObject, 'components' | 'paths'>>;
get swaggerDocuments(): Array<Omit<OpenAPIObject, 'components' | 'paths'>> {
return this._swaggerDocuments;
}
addSwaggerDocument(value: Omit<OpenAPIObject, 'components' | 'paths'>): void {
this._swaggerDocuments.push(value); // you might want to go with immutable way but just to give you an idea
}
}
- 创建一个
SwaggerDocumentModule
并使其成为全球性的。然后提供并SwaggerDocumentService
导出SwaggerDocumentModule
@Global()
@Module({
providers: [SwaggerDocumentService],
exports: [SwaggerDocumentService]
})
export class SwaggerDocumentModule
- 导入
SwaggerDocumentModule
_AppModule
@Module({
...
imports: [SwaggerDocumentModule]
})
export class AppModule
- 在
main.ts
中,获取 的实例SwaggerDocumentService
并设置文档。
async bootstrap() {
const app = await NestFactory.create(AppModule);
const swaggerDocumentService = app.get<SwaggerDocumentService>(SwaggerDocumentService); // might want to check for null
// setup your options with DocumentBuilder
const options = new DocumentBuilder()...;
swaggerDocumentService.addSwaggerDocument(options);
}
- 利用
SwaggerDocumentService
@Injectable()
export class AppService {
constructor(private readonly swaggerDocumentService: SwaggerDocumentService) {
swaggerDocumentService.swaggerDocuments; // will be the array of Swagger Document
}
}
推荐阅读
- node.js - 从另一个脚本调用方法抛出找不到模块
- sql - 设置和声明语句
- react-native - 我如何在文本输入中显示从时间选择器中选择的时间?
- android - 尝试通过 Cordova 插件为 Firebase Cloud Messaging 推送通知时,设备令牌为空
- functional-programming - Clojure 排序字符串值 - 不区分大小写
- java - 内存中发生了什么,一个新进程是否总是在 Java 中打开一个新的 JVM?
- julia - LoadError: MethodError: convert(::Type{Union{}}, ::LinearAlgebra.Adjoint{Float64,Array{Float64,1}}) 不明确
- powershell - 带有 Powershell 的 IE 自动化发送 ENTER 键
- redis - Redis Sentinel Rename-Command Ignored
- angular - Angular formly-expressionProperties 和 hideExpression 有什么区别