【问题标题】:NestJs-Swagger - Is it possible to list all Swagger Documents in a NestExpressApplication?NestJs-Swagger - 是否可以在 NestExpressApplication 中列出所有 Swagger 文档?
【发布时间】:2020-04-09 18:39:18
【问题描述】:

我将 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/'
  }
]

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

【问题讨论】:

  • 这不是你用DocumentBuilder构建的options吗?
  • 是的,但是有没有办法从app.service.ts 访问这些信息?

标签: swagger nestjs


【解决方案1】:

我刚刚浏览了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 并将其设为全局。然后在SwaggerDocumentModule中提供并导出SwaggerDocumentService
@Global()
@Module({
   providers: [SwaggerDocumentService],
   exports: [SwaggerDocumentService]
})
export class SwaggerDocumentModule
  1. AppModule 中导入SwaggerDocumentModule
@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
   }
}

【讨论】:

    猜你喜欢
    • 2021-09-07
    • 1970-01-01
    • 2019-09-16
    • 2021-10-18
    • 2021-10-03
    • 2022-08-12
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多