首页 > 解决方案 > NestJs-Swagger - 是否可以在 NestExpressApplication 中列出所有 Swagger 文档?

问题描述

我将NestJsSwaggerModule一起使用,我想在应用程序初始化后列出所有文档。

就像是:

[
  {
    title: 'Admin',
    description: 'Admin endpoints',
    version: '1.2.3',
    url: 'admin/123/'
  },
  {
    title: 'Resources',
    description: 'Resources endpoints',
    version: '1.2.5',
    url: 'admin/125/'
  }
]

是否有我可以访问的具有这些文档信息的对象,还是我必须自己创建它?

标签: swaggernestjs

解决方案


我刚刚浏览了NestJS文档,似乎无法在运行时添加提供程序。但这并非不可能。

  1. 创建服务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
   }
}
  1. 创建一个SwaggerDocumentModule并使其成为全球性的。然后提供并SwaggerDocumentService导出SwaggerDocumentModule
@Global()
@Module({
   providers: [SwaggerDocumentService],
   exports: [SwaggerDocumentService]
})
export class SwaggerDocumentModule
  1. 导入SwaggerDocumentModule_AppModule
@Module({
   ...
   imports: [SwaggerDocumentModule]
})
export class AppModule
  1. 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);
}
  1. 利用SwaggerDocumentService
@Injectable()
export class AppService {
   constructor(private readonly swaggerDocumentService: SwaggerDocumentService) {
      swaggerDocumentService.swaggerDocuments; // will be the array of Swagger Document
   }
}

推荐阅读