SwaggerUiSetupMiddleware.ts 1.3 KB

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