SwaggerUiSetupMiddleware.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import swaggerJsDoc, { OAS3Options, Options, SecurityRequirement } from 'swagger-jsdoc';
  2. import { Middleware } from '../base/http';
  3. import swaggerUi from 'swagger-ui-express';
  4. import { $$ } from '../base/i18n';
  5. import { MiddlewareOrder } from './MiddlewareOrder';
  6. class SwaggerUiSetupMiddleware extends Middleware {
  7. protected order = MiddlewareOrder.SwaggerUiSetupMiddleware;
  8. protected route = this.context.swaggerRoute;
  9. protected action: any = this.getSetup();
  10. private getSetup(): any {
  11. if(!this.context.swaggerDocsPath)
  12. return (req: Request, res: Response, next: any) => { next(); };
  13. const swaggerOptions : OAS3Options = {
  14. swaggerDefinition: {
  15. openapi: '3.0.1',
  16. info: {
  17. title: this.context.swaggerTitle!,
  18. version: this.context.swaggerApiVersion!,
  19. description: this.context.swaggerDescription!,
  20. },
  21. servers: [
  22. { url: this.context.host }
  23. ],
  24. },
  25. apis: [this.context.swaggerDocsPath],
  26. };
  27. if(this.context.swaggerComponents)
  28. swaggerOptions.swaggerDefinition!.components = this.context.swaggerComponents;
  29. if(this.context.swaggerSecurity)
  30. swaggerOptions.swaggerDefinition!.security = this.context.swaggerSecurity as SecurityRequirement[];
  31. const swaggerDocs = swaggerJsDoc(swaggerOptions as Options);
  32. this.context.logInfo($$('org.crazydoctor.expressts.swagger.registered', { path: this.context.swaggerRoute }));
  33. return swaggerUi.setup(swaggerDocs);
  34. }
  35. }
  36. export { SwaggerUiSetupMiddleware };