Browse Source

Swagger middlewares

CrazyDoctor 2 months ago
parent
commit
c69578ba08

+ 2 - 1
.gitignore

@@ -1,3 +1,4 @@
 .idea/
 node_modules/
-*.iml
+*.iml
+test/

+ 17 - 7
dist/base/util/Guid.js

@@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
 }) : function(o, v) {
     o["default"] = v;
 });
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
+var __importStar = (this && this.__importStar) || (function () {
+    var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function (o) {
+            var ar = [];
+            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+            return ar;
+        };
+        return ownKeys(o);
+    };
+    return function (mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+        __setModuleDefault(result, mod);
+        return result;
+    };
+})();
 Object.defineProperty(exports, "__esModule", { value: true });
 exports.Guid = void 0;
 const crypto = __importStar(require("crypto"));

+ 1 - 1
dist/base/util/Guid.js.map

@@ -1 +1 @@
-{"version":3,"file":"Guid.js","sourceRoot":"","sources":["../../../lib/base/util/Guid.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAiC;AAEjC,MAAM,IAAI;IACF,MAAM,CAAC,GAAG;QAChB,OAAO,MAAM,CAAC,UAAU,EAAE,CAAC;IAC5B,CAAC;CACD;AAEQ,oBAAI"}
+{"version":3,"file":"Guid.js","sourceRoot":"","sources":["../../../lib/base/util/Guid.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,+CAAiC;AAEjC,MAAM,IAAI;IACF,MAAM,CAAC,GAAG;QAChB,OAAO,MAAM,CAAC,UAAU,EAAE,CAAC;IAC5B,CAAC;CACD;AAEQ,oBAAI"}

+ 0 - 1
dist/middlewares/ExpressJsonMiddleware.d.ts

@@ -1,4 +1,3 @@
-/// <reference types="connect" />
 import { Middleware } from '../base/http';
 declare class ExpressJsonMiddleware extends Middleware {
     protected order: number;

+ 0 - 1
dist/middlewares/ExpressUrlencodedMiddleware.d.ts

@@ -1,4 +1,3 @@
-/// <reference types="connect" />
 import { Middleware } from '../base/http';
 declare class ExpressUrlencodedMiddleware extends Middleware {
     protected order: number;

+ 0 - 2
dist/middlewares/SessionMiddleware.d.ts

@@ -1,5 +1,3 @@
-/// <reference types="qs" />
-/// <reference types="express" />
 import { Middleware } from '../base/http';
 declare class SessionMiddleware extends Middleware {
     protected order: number;

+ 7 - 0
dist/middlewares/SwaggerUiServeMiddleware.d.ts

@@ -0,0 +1,7 @@
+import { Middleware } from '../base/http';
+declare class SwaggerUiServeMiddleware extends Middleware {
+    protected order: number;
+    protected route: any;
+    protected action: any;
+}
+export default SwaggerUiServeMiddleware;

+ 17 - 0
dist/middlewares/SwaggerUiServeMiddleware.js

@@ -0,0 +1,17 @@
+"use strict";
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+const http_1 = require("../base/http");
+const swagger_ui_express_1 = __importDefault(require("swagger-ui-express"));
+class SwaggerUiServeMiddleware extends http_1.Middleware {
+    constructor() {
+        super(...arguments);
+        this.order = -97;
+        this.route = this.context.swaggerRoute;
+        this.action = swagger_ui_express_1.default.serve;
+    }
+}
+exports.default = SwaggerUiServeMiddleware;
+//# sourceMappingURL=SwaggerUiServeMiddleware.js.map

+ 1 - 0
dist/middlewares/SwaggerUiServeMiddleware.js.map

@@ -0,0 +1 @@
+{"version":3,"file":"SwaggerUiServeMiddleware.js","sourceRoot":"","sources":["../../lib/middlewares/SwaggerUiServeMiddleware.ts"],"names":[],"mappings":";;;;;AAAA,uCAA0C;AAC1C,4EAA2C;AAE3C,MAAM,wBAAyB,SAAQ,iBAAU;IAAjD;;QACW,UAAK,GAAG,CAAC,EAAE,CAAC;QACZ,UAAK,GAAG,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC;QAClC,WAAM,GAAQ,4BAAS,CAAC,KAAK,CAAC;IACzC,CAAC;CAAA;AAED,kBAAe,wBAAwB,CAAC"}

+ 8 - 0
dist/middlewares/SwaggerUiSetupMiddleware.d.ts

@@ -0,0 +1,8 @@
+import { Middleware } from '../base/http';
+declare class SwaggerUiSetupMiddleware extends Middleware {
+    protected order: number;
+    protected route: any;
+    protected action: any;
+    private getSetup;
+}
+export default SwaggerUiSetupMiddleware;

+ 44 - 0
dist/middlewares/SwaggerUiSetupMiddleware.js

@@ -0,0 +1,44 @@
+"use strict";
+var __importDefault = (this && this.__importDefault) || function (mod) {
+    return (mod && mod.__esModule) ? mod : { "default": mod };
+};
+Object.defineProperty(exports, "__esModule", { value: true });
+const swagger_jsdoc_1 = __importDefault(require("swagger-jsdoc"));
+const http_1 = require("../base/http");
+const swagger_ui_express_1 = __importDefault(require("swagger-ui-express"));
+const i18n_1 = require("../base/i18n");
+class SwaggerUiSetupMiddleware extends http_1.Middleware {
+    constructor() {
+        super(...arguments);
+        this.order = -96;
+        this.route = this.context.swaggerRoute;
+        this.action = this.getSetup();
+    }
+    getSetup() {
+        if (!this.context.swaggerDocsPath)
+            return (req, res, next) => { next(); };
+        const swaggerOptions = {
+            swaggerDefinition: {
+                openapi: '3.0.1',
+                info: {
+                    title: this.context.swaggerTitle,
+                    version: this.context.swaggerApiVersion,
+                    description: this.context.swaggerDescription,
+                },
+                servers: [
+                    { url: this.context.host }
+                ],
+            },
+            apis: [this.context.swaggerDocsPath],
+        };
+        if (this.context.swaggerComponents)
+            swaggerOptions.swaggerDefinition.components = this.context.swaggerComponents;
+        if (this.context.swaggerSecurity)
+            swaggerOptions.swaggerDefinition.security = this.context.swaggerSecurity;
+        const swaggerDocs = (0, swagger_jsdoc_1.default)(swaggerOptions);
+        this.context.logInfo((0, i18n_1.$$)('org.crazydoctor.expressts.swagger.registered', { path: this.context.swaggerRoute }));
+        return swagger_ui_express_1.default.setup(swaggerDocs);
+    }
+}
+exports.default = SwaggerUiSetupMiddleware;
+//# sourceMappingURL=SwaggerUiSetupMiddleware.js.map

+ 1 - 0
dist/middlewares/SwaggerUiSetupMiddleware.js.map

@@ -0,0 +1 @@
+{"version":3,"file":"SwaggerUiSetupMiddleware.js","sourceRoot":"","sources":["../../lib/middlewares/SwaggerUiSetupMiddleware.ts"],"names":[],"mappings":";;;;;AAAA,kEAAwF;AACxF,uCAA0C;AAC1C,4EAA2C;AAC3C,uCAAkC;AAElC,MAAM,wBAAyB,SAAQ,iBAAU;IAAjD;;QACW,UAAK,GAAG,CAAC,EAAE,CAAC;QACZ,UAAK,GAAG,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC;QAClC,WAAM,GAAQ,IAAI,CAAC,QAAQ,EAAE,CAAC;IAiCzC,CAAC;IA/BQ,QAAQ;QACf,IAAG,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe;YAC/B,OAAO,CAAC,GAAY,EAAE,GAAa,EAAE,IAAS,EAAE,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;QAEhE,MAAM,cAAc,GAAiB;YACpC,iBAAiB,EAAE;gBAClB,OAAO,EAAE,OAAO;gBAChB,IAAI,EAAE;oBACL,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,YAAa;oBACjC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,iBAAkB;oBACxC,WAAW,EAAE,IAAI,CAAC,OAAO,CAAC,kBAAmB;iBAC7C;gBACD,OAAO,EAAE;oBACR,EAAE,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;iBAC1B;aACD;YACD,IAAI,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC;SACpC,CAAC;QAEF,IAAG,IAAI,CAAC,OAAO,CAAC,iBAAiB;YAChC,cAAc,CAAC,iBAAkB,CAAC,UAAU,GAAG,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC;QAC/E,IAAG,IAAI,CAAC,OAAO,CAAC,eAAe;YAC9B,cAAc,CAAC,iBAAkB,CAAC,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,eAAwC,CAAC;QAEpG,MAAM,WAAW,GAAG,IAAA,uBAAY,EAAC,cAAyB,CAAC,CAAC;QAE5D,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAA,SAAE,EAAC,8CAA8C,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC;QAE9G,OAAO,4BAAS,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IAErC,CAAC;CACD;AAED,kBAAe,wBAAwB,CAAC"}

+ 3 - 1
dist/resources/i18n.json

@@ -2,6 +2,8 @@
   "en_US": {
     "org.crazydoctor.expressts.start": "org.crazydoctor.expressts server started on port {port}",
     "org.crazydoctor.expressts.httpError.500": "Internal server error",
-    "org.crazydoctor.expressts.httpError.404": "Page {url} not found"
+    "org.crazydoctor.expressts.httpError.404": "Page {url} not found",
+    "org.crazydoctor.expressts.swagger.registered": "Swagger documentation is available on {path}",
+    "org.crazydoctor.expressts.swagger.routeGenerated": "Swagger documentation for route '{route}' generated!"
   }
 }

+ 0 - 1
dist/server/Server.d.ts

@@ -46,7 +46,6 @@ declare class Server {
     log(message: Message): void;
     private get;
     private post;
-    private registerSwaggerMiddleware;
     registerRoutes(dir: string): Promise<Server>;
     registerMiddlewares(dir: string): Promise<Server>;
     getLogger(): Logger;

+ 21 - 37
dist/server/Server.js

@@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
 }) : function(o, v) {
     o["default"] = v;
 });
-var __importStar = (this && this.__importStar) || function (mod) {
-    if (mod && mod.__esModule) return mod;
-    var result = {};
-    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
-    __setModuleDefault(result, mod);
-    return result;
-};
+var __importStar = (this && this.__importStar) || (function () {
+    var ownKeys = function(o) {
+        ownKeys = Object.getOwnPropertyNames || function (o) {
+            var ar = [];
+            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+            return ar;
+        };
+        return ownKeys(o);
+    };
+    return function (mod) {
+        if (mod && mod.__esModule) return mod;
+        var result = {};
+        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+        __setModuleDefault(result, mod);
+        return result;
+    };
+})();
 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
     return new (P || (P = Promise))(function (resolve, reject) {
@@ -50,8 +60,6 @@ const exceptions_3 = require("../base/exceptions");
 const exceptions_4 = require("../base/exceptions");
 const exceptions_5 = require("../base/exceptions");
 const websocket_1 = require("../base/websocket");
-const swagger_jsdoc_1 = __importDefault(require("swagger-jsdoc"));
-const swagger_ui_express_1 = __importDefault(require("swagger-ui-express"));
 /** @sealed */
 class Server {
     constructor(properties) {
@@ -146,6 +154,8 @@ class Server {
         }
     }
     registerRoutesDocumentation() {
+        if (!this.swaggerDocsPath)
+            return this;
         for (const routeName in this.httpHandlers) {
             const route = this.httpHandlers[routeName];
             if (!(route instanceof http_1.Route))
@@ -155,9 +165,9 @@ class Server {
             if (![http_1.HttpMethod.GET, http_1.HttpMethod.POST].includes(route.getMethod()))
                 throw new exceptions_2.IncorrectMethodException();
             const docs = route.getDocumentation();
-            if (this.swaggerDocsPath && docs.length > 0) {
+            if (docs.length > 0) {
                 fs_1.default.appendFileSync(this.swaggerDocsPath, `${docs}\n`);
-                this.logInfo(`Swagger documentation for route '${route.getRoute()}' generated!`);
+                this.logInfo((0, i18n_1.$$)('org.crazydoctor.expressts.swagger.routeGenerated', { route: route.getRoute() }));
             }
         }
         return this;
@@ -222,31 +232,6 @@ class Server {
         this.instance.post(route.getRoute(), route.getAction());
         return this;
     }
-    registerSwaggerMiddleware() {
-        if (!this.swaggerDocsPath)
-            return this;
-        const swaggerOptions = {
-            swaggerDefinition: {
-                openapi: '3.0.1',
-                info: {
-                    title: this.swaggerTitle,
-                    version: this.swaggerApiVersion,
-                    description: this.swaggerDescription,
-                },
-                servers: [
-                    { url: this.host }
-                ],
-            },
-            apis: [this.swaggerDocsPath],
-        };
-        if (this.swaggerComponents)
-            swaggerOptions.swaggerDefinition.components = this.swaggerComponents;
-        if (this.swaggerSecurity)
-            swaggerOptions.swaggerDefinition.security = this.swaggerSecurity;
-        const swaggerDocs = (0, swagger_jsdoc_1.default)(swaggerOptions);
-        this.instance.use(this.swaggerRoute, swagger_ui_express_1.default.serve, swagger_ui_express_1.default.setup(swaggerDocs));
-        return this;
-    }
     registerRoutes(dir) {
         return __awaiter(this, void 0, void 0, function* () {
             const files = fs_1.default.readdirSync(dir, { recursive: true, encoding: 'utf8' });
@@ -296,7 +281,6 @@ class Server {
         if (!this.initialized)
             throw new exceptions_5.ServerNotInitializedException();
         this.registerRoutesDocumentation();
-        this.registerSwaggerMiddleware();
         this.processHttpHandlers();
         const cb = () => {
             this.logInfo((0, i18n_1.$$)('org.crazydoctor.expressts.start', { 'port': this.port }));

File diff suppressed because it is too large
+ 0 - 0
dist/server/Server.js.map


+ 10 - 0
lib/middlewares/SwaggerUiServeMiddleware.ts

@@ -0,0 +1,10 @@
+import { Middleware } from '../base/http';
+import swaggerUi from 'swagger-ui-express';
+
+class SwaggerUiServeMiddleware extends Middleware {
+	protected order = -97;
+	protected route = this.context.swaggerRoute;
+	protected action: any = swaggerUi.serve;
+}
+
+export default SwaggerUiServeMiddleware;

+ 44 - 0
lib/middlewares/SwaggerUiSetupMiddleware.ts

@@ -0,0 +1,44 @@
+import swaggerJsDoc, { OAS3Options, Options, SecurityRequirement } from 'swagger-jsdoc';
+import { Middleware } from '../base/http';
+import swaggerUi from 'swagger-ui-express';
+import { $$ } from '../base/i18n';
+
+class SwaggerUiSetupMiddleware extends Middleware {
+	protected order = -96;
+	protected route = this.context.swaggerRoute;
+	protected action: any = this.getSetup();
+
+	private getSetup(): any {
+		if(!this.context.swaggerDocsPath)
+			return (req: Request, res: Response, next: any) => { next(); };
+
+		const swaggerOptions : OAS3Options = {
+			swaggerDefinition: {
+				openapi: '3.0.1',
+				info: {
+					title: this.context.swaggerTitle!,
+					version: this.context.swaggerApiVersion!,
+					description: this.context.swaggerDescription!,
+				},
+				servers: [
+					{ url: this.context.host }
+				],
+			},
+			apis: [this.context.swaggerDocsPath],
+		};
+
+		if(this.context.swaggerComponents)
+			swaggerOptions.swaggerDefinition!.components = this.context.swaggerComponents;
+		if(this.context.swaggerSecurity)
+			swaggerOptions.swaggerDefinition!.security = this.context.swaggerSecurity as SecurityRequirement[];
+
+		const swaggerDocs = swaggerJsDoc(swaggerOptions as Options);
+
+		this.context.logInfo($$('org.crazydoctor.expressts.swagger.registered', { path: this.context.swaggerRoute }));
+
+		return swaggerUi.setup(swaggerDocs);
+
+	}
+}
+
+export default SwaggerUiSetupMiddleware;

+ 3 - 1
lib/resources/i18n.json

@@ -2,6 +2,8 @@
   "en_US": {
     "org.crazydoctor.expressts.start": "org.crazydoctor.expressts server started on port {port}",
     "org.crazydoctor.expressts.httpError.500": "Internal server error",
-    "org.crazydoctor.expressts.httpError.404": "Page {url} not found"
+    "org.crazydoctor.expressts.httpError.404": "Page {url} not found",
+    "org.crazydoctor.expressts.swagger.registered": "Swagger documentation is available on {path}",
+    "org.crazydoctor.expressts.swagger.routeGenerated": "Swagger documentation for route '{route}' generated!"
   }
 }

+ 6 - 34
lib/server/Server.ts

@@ -1,4 +1,4 @@
-import express, {Express} from 'express';
+import express, { Express } from 'express';
 import { Middleware, Route, HttpMethod, HttpHandler } from '../base/http';
 import { RouteNotSetException } from '../base/exceptions';
 import { IncorrectMethodException } from '../base/exceptions';
@@ -141,6 +141,9 @@ class Server {
 	}
 
 	private registerRoutesDocumentation(): Server {
+		if(!this.swaggerDocsPath)
+			return this;
+		
 		for(const routeName in this.httpHandlers) {
 			const route = this.httpHandlers[routeName];
 			if(!(route instanceof Route))
@@ -154,9 +157,9 @@ class Server {
 	
 			const docs = route.getDocumentation();
 	
-			if(this.swaggerDocsPath && docs.length > 0) {
+			if(docs.length > 0) {
 				fs.appendFileSync(this.swaggerDocsPath, `${docs}\n`);
-				this.logInfo(`Swagger documentation for route '${route.getRoute()}' generated!`);
+				this.logInfo($$('org.crazydoctor.expressts.swagger.routeGenerated', { route: route.getRoute() }));
 			}
 		}
 		return this;
@@ -229,36 +232,6 @@ class Server {
 		return this;
 	}
 
-	private registerSwaggerMiddleware(): Server {
-		if(!this.swaggerDocsPath)
-			return this;
-
-		const swaggerOptions : OAS3Options = {
-			swaggerDefinition: {
-				openapi: '3.0.1',
-				info: {
-					title: this.swaggerTitle!,
-					version: this.swaggerApiVersion!,
-					description: this.swaggerDescription!,
-				},
-				servers: [
-					{ url: this.host }
-				],
-			},
-			apis: [this.swaggerDocsPath],
-		};
-
-		if(this.swaggerComponents)
-			swaggerOptions.swaggerDefinition!.components = this.swaggerComponents;
-		if(this.swaggerSecurity)
-			swaggerOptions.swaggerDefinition!.security = this.swaggerSecurity as SecurityRequirement[];
-
-		const swaggerDocs = swaggerJsDoc(swaggerOptions as Options);
-
-		this.instance.use(this.swaggerRoute!, swaggerUi.serve, swaggerUi.setup(swaggerDocs));
-		return this;
-	}
-
 	public async registerRoutes(dir: string): Promise<Server> {
 		const files = fs.readdirSync(dir, { recursive: true, encoding: 'utf8' });
 
@@ -308,7 +281,6 @@ class Server {
 		if(!this.initialized)
 			throw new ServerNotInitializedException();
 		this.registerRoutesDocumentation();
-		this.registerSwaggerMiddleware();
 		this.processHttpHandlers();
 		const cb = (): void => {
 			this.logInfo($$('org.crazydoctor.expressts.start', { 'port': this.port }));

File diff suppressed because it is too large
+ 233 - 134
package-lock.json


+ 0 - 1
package.json

@@ -11,7 +11,6 @@
   },
   "dependencies": {
     "@types/express": "^4.17.17",
-    "@types/pino": "^7.0.5",
     "@types/swagger-jsdoc": "^6.0.4",
     "@types/swagger-ui-express": "^4.1.6",
     "@types/ws": "^8.5.10",

Some files were not shown because too many files changed in this diff