我正在将 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/'
}
]
我可以到达的物体上有那些文档的信息吗?还是我必须自己创建它?
答案 0 :(得分:1)
我刚刚浏览了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
}
}