NestJs-Swagger-是否可以在NestExpressApplication中列出所有Swagger文档?

时间:2019-12-17 09:30:33

标签: swagger nestjs

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

我可以到达的物体上有那些文档的信息吗?还是我必须自己创建它?

1 个答案:

答案 0 :(得分: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并将其设置为全局。然后在SwaggerDocumentService
  2. 中提供和导出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
   }
}