Server.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. import express, { Express } from 'express';
  2. import { Middleware, Route, HttpMethod, HttpHandler } from '../base/http';
  3. import { RouteNotSetException } from '../base/exceptions';
  4. import { IncorrectMethodException } from '../base/exceptions';
  5. import { Logger, Message, MessageTypes } from '../base/logger';
  6. import { ServerProperties } from './ServerProperties';
  7. import { i18nLoader, $$ } from '../base/i18n';
  8. import path from 'path';
  9. import fs from 'fs';
  10. import http from 'http';
  11. import { Server as WebSocketServer, WebSocket as WS } from 'ws';
  12. import { InvalidMiddlewareException } from '../base/exceptions';
  13. import { InvalidRouteException } from '../base/exceptions';
  14. import { ServerNotInitializedException } from '../base/exceptions';
  15. import { WebSocketHandler } from '../base/websocket';
  16. import swaggerJsDoc, { OAS3Options, Options, SecurityRequirement } from 'swagger-jsdoc';
  17. import swaggerUi from 'swagger-ui-express';
  18. /** @sealed */
  19. class Server {
  20. private instance: Express;
  21. private httpServer: http.Server;
  22. private readonly port: number;
  23. private readonly host: string;
  24. private readonly logger: Logger;
  25. private i18n: i18nLoader;
  26. public static readonly i18nDefaultPath = '../resources/i18n.json';
  27. public static readonly defaultMiddlewaresPath = '../middlewares';
  28. public static readonly defaultRoutesPath = '../routes';
  29. private readonly httpHandlers: {[key: string]: HttpHandler};
  30. private readonly wsHandlers: {[url: string]: WebSocketHandler};
  31. private readonly wsServers: {[url: string]: WebSocketServer};
  32. private initialized: boolean;
  33. private readonly i18nPath?: string;
  34. private readonly middlewaresPath?: string;
  35. private readonly routesPath?: string;
  36. private readonly viewEngine?: string;
  37. private readonly viewsPath?: string;
  38. private readonly options?: {[key: string]: any};
  39. private readonly swaggerComponents? : object;
  40. private readonly swaggerSecurity? : object;
  41. private readonly swaggerDocsPath? : string;
  42. private readonly swaggerTitle?: string;
  43. private readonly swaggerDescription?: string;
  44. private readonly swaggerApiVersion?: string;
  45. private readonly swaggerRoute?: string;
  46. public constructor(properties: ServerProperties) {
  47. this.instance = express();
  48. this.httpServer = http.createServer(this.instance);
  49. this.port = properties.port;
  50. this.host = properties.host || `http://localhost:${this.port}`;
  51. this.i18n = i18nLoader.getInstance();
  52. if(properties.locale)
  53. this.i18n.setLocale(properties.locale);
  54. this.logger = new Logger();
  55. this.httpHandlers = {};
  56. this.wsHandlers = properties.wsHandlers || {};
  57. this.wsServers = {};
  58. this.i18nPath = properties.i18nPath;
  59. this.middlewaresPath = properties.middlewaresPath;
  60. this.routesPath = properties.routesPath;
  61. this.viewEngine = properties.viewEngine;
  62. this.viewsPath = properties.viewsPath;
  63. this.options = properties.options;
  64. if(properties.swagger) {
  65. this.swaggerDocsPath = properties.swagger?.docsPath;
  66. this.swaggerTitle = properties.swagger?.title || 'API Documentation';
  67. this.swaggerDescription = properties.swagger?.description || 'API Documentation';
  68. this.swaggerApiVersion = properties.swagger?.version ||'1.0.0';
  69. this.swaggerRoute = properties.swagger?.route || '/api-docs';
  70. this.swaggerComponents = properties.swagger?.components;
  71. this.swaggerSecurity = properties.swagger?.security;
  72. }
  73. this.initialized = false;
  74. }
  75. public async init(): Promise<Server> {
  76. if(this.viewEngine)
  77. this.instance.set('view engine', this.viewEngine);
  78. if(this.viewsPath)
  79. this.instance.set('views', this.viewsPath);
  80. this.i18n.load(path.resolve(__dirname, Server.i18nDefaultPath));
  81. await this.registerMiddlewares(path.resolve(__dirname, Server.defaultMiddlewaresPath));
  82. await this.registerRoutes(path.resolve(__dirname, Server.defaultRoutesPath));
  83. await this.postInit();
  84. this.initialized = true;
  85. return this;
  86. }
  87. private async postInit(): Promise<void> {
  88. if(this.i18nPath)
  89. this.i18n.load(this.i18nPath);
  90. if(this.middlewaresPath)
  91. await this.registerMiddlewares(this.middlewaresPath);
  92. if(this.routesPath)
  93. await this.registerRoutes(this.routesPath);
  94. if(this.swaggerDocsPath)
  95. fs.writeFileSync(this.swaggerDocsPath, '');
  96. if(Object.keys(this.wsHandlers).length > 0) {
  97. this.registerWsServers();
  98. this.applyWsHandlers();
  99. }
  100. }
  101. private processHttpHandlers(): void {
  102. const handlers: HttpHandler[] = [];
  103. for(const key in this.httpHandlers)
  104. handlers.push(this.httpHandlers[key]);
  105. handlers.sort((a, b) => a.getOrder() - b.getOrder());
  106. for(const handler of handlers) {
  107. if(handler instanceof Middleware)
  108. this.addMiddleware(handler);
  109. else if (handler instanceof Route)
  110. this.addRoute(handler);
  111. }
  112. }
  113. public addMiddleware(middleware: Middleware): Server {
  114. if(middleware.getRoute() != null)
  115. this.instance.use(<string>middleware.getRoute(), middleware.getAction());
  116. else
  117. this.instance.use(middleware.getAction());
  118. return this;
  119. }
  120. public addRoute(route: Route): Server {
  121. if(route.getRoute() == null)
  122. throw new RouteNotSetException();
  123. switch(route.getMethod()) {
  124. case HttpMethod.GET:
  125. return this.get(route);
  126. case HttpMethod.POST:
  127. return this.post(route);
  128. default:
  129. throw new IncorrectMethodException();
  130. }
  131. }
  132. private registerRoutesDocumentation(): Server {
  133. if(!this.swaggerDocsPath)
  134. return this;
  135. for(const routeName in this.httpHandlers) {
  136. const route = this.httpHandlers[routeName];
  137. if(!(route instanceof Route))
  138. continue;
  139. if(route.getRoute() == null)
  140. throw new RouteNotSetException();
  141. if(![HttpMethod.GET, HttpMethod.POST].includes(route.getMethod()))
  142. throw new IncorrectMethodException();
  143. const docs = route.getDocumentation();
  144. if(docs.length > 0) {
  145. fs.appendFileSync(this.swaggerDocsPath, `${docs}\n`);
  146. this.logInfo($$('org.crazydoctor.expressts.swagger.routeGenerated', { route: route.getRoute() }));
  147. }
  148. }
  149. return this;
  150. }
  151. public registerWsServers(): Server {
  152. for(const url of Object.keys(this.wsHandlers)) {
  153. const wsServer = this.wsServers[url] = new WebSocketServer({ noServer: true });
  154. const wsHandler = this.wsHandlers[url];
  155. wsServer.on(WebSocketHandler.Event.CONNECTION, (ws: WS) => {
  156. wsHandler.onConnect(ws);
  157. ws.on(WebSocketHandler.Event.MESSAGE, wsHandler.onMessage);
  158. ws.on(WebSocketHandler.Event.ERROR, wsHandler.onError);
  159. ws.on(WebSocketHandler.Event.CLOSE, wsHandler.onClose);
  160. });
  161. }
  162. return this;
  163. }
  164. public applyWsHandlers(): Server {
  165. this.httpServer.on('upgrade', (request, socket, head) => {
  166. const url = request.url?.split('?')[0];
  167. if(url && this.wsHandlers[url] && this.wsServers[url]) {
  168. const wsServer = this.wsServers[url];
  169. wsServer.handleUpgrade(request, socket, head, (ws) => {
  170. wsServer.emit(WebSocketHandler.Event.CONNECTION, ws, request);
  171. });
  172. } else {
  173. socket.destroy();
  174. }
  175. });
  176. return this;
  177. }
  178. public getWsConnections(url: string): Set<WS> | null {
  179. const wsServer = this.wsServers[url];
  180. return wsServer ? wsServer.clients : null;
  181. }
  182. public logInfo(message: string): void {
  183. this.logger.getLogger().info(message);
  184. }
  185. public logError(message: string): void {
  186. this.logger.getLogger().error(message);
  187. }
  188. public logWarn(message: string): void {
  189. this.logger.getLogger().warn(message);
  190. }
  191. public log(message: Message): void {
  192. switch(message.type) {
  193. case MessageTypes.WARNING:
  194. return this.logWarn(message.text);
  195. case MessageTypes.ERROR:
  196. return this.logError(message.text);
  197. default:
  198. return this.logInfo(message.text);
  199. }
  200. }
  201. private get(route: Route): Server {
  202. this.instance.get(<string>route.getRoute(), route.getAction());
  203. return this;
  204. }
  205. private post(route: Route): Server {
  206. this.instance.post(<string>route.getRoute(), route.getAction());
  207. return this;
  208. }
  209. public async registerRoutes(dir: string): Promise<Server> {
  210. const files = fs.readdirSync(dir, { recursive: true, encoding: 'utf8' });
  211. for(const file of files) {
  212. if(/\.js$/.test(file)) {
  213. const {default: RouteClass} = await import(path.join(dir, file));
  214. if(RouteClass.prototype instanceof Route) {
  215. this.httpHandlers[RouteClass.name] = <HttpHandler>new RouteClass(this);
  216. } else throw new InvalidRouteException(file);
  217. }
  218. }
  219. return this;
  220. }
  221. public async registerMiddlewares(dir: string): Promise<Server> {
  222. const files = fs.readdirSync(dir, { recursive: true, encoding: 'utf8' });
  223. for(const file of files) {
  224. if(/\.js$/.test(file)) {
  225. const {default: MiddlewareClass} = await import(path.join(dir, file));
  226. if(MiddlewareClass.prototype instanceof Middleware) {
  227. this.httpHandlers[MiddlewareClass.name] = <HttpHandler>new MiddlewareClass(this);
  228. } else throw new InvalidMiddlewareException(file);
  229. }
  230. }
  231. return this;
  232. }
  233. public getLogger(): Logger {
  234. return this.logger;
  235. }
  236. public i18nLoad(path: string): Server {
  237. this.i18n.load(path);
  238. return this;
  239. }
  240. public getHost(): string {
  241. return this.host;
  242. }
  243. public getOption(key: string): any {
  244. return this.options ? this.options[key] || null : null;
  245. }
  246. public start(callback?: () => any): void {
  247. if(!this.initialized)
  248. throw new ServerNotInitializedException();
  249. this.registerRoutesDocumentation();
  250. this.processHttpHandlers();
  251. const cb = (): void => {
  252. this.logInfo($$('org.crazydoctor.expressts.start', { 'port': this.port }));
  253. if(callback) callback();
  254. };
  255. this.httpServer.listen(this.port, cb);
  256. }
  257. }
  258. export { Server };