Server.ts 9.1 KB

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