Server.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 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 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. }
  69. this.initialized = false;
  70. }
  71. public async init(): Promise<Server> {
  72. if(this.viewEngine)
  73. this.instance.set('view engine', this.viewEngine);
  74. if(this.viewsPath)
  75. this.instance.set('views', this.viewsPath);
  76. this.i18n.load(path.resolve(__dirname, Server.i18nDefaultPath));
  77. await this.registerMiddlewares(path.resolve(__dirname, Server.defaultMiddlewaresPath));
  78. await this.registerRoutes(path.resolve(__dirname, Server.defaultRoutesPath));
  79. await this.postInit();
  80. this.initialized = true;
  81. return this;
  82. }
  83. private async postInit(): Promise<void> {
  84. if(this.i18nPath)
  85. this.i18n.load(this.i18nPath);
  86. if(this.middlewaresPath)
  87. await this.registerMiddlewares(this.middlewaresPath);
  88. if(this.routesPath)
  89. await this.registerRoutes(this.routesPath);
  90. if(this.swaggerDocsPath)
  91. fs.writeFileSync(this.swaggerDocsPath, '');
  92. if(Object.keys(this.wsHandlers).length > 0) {
  93. this.registerWsServers();
  94. this.applyWsHandlers();
  95. }
  96. }
  97. private processHttpHandlers(): void {
  98. const handlers: HttpHandler[] = [];
  99. for(const key in this.httpHandlers)
  100. handlers.push(this.httpHandlers[key]);
  101. handlers.sort((a, b) => a.getOrder() - b.getOrder());
  102. for(const handler of handlers) {
  103. if(handler instanceof Middleware)
  104. this.addMiddleware(handler);
  105. else if (handler instanceof Route)
  106. this.addRoute(handler);
  107. }
  108. }
  109. public addMiddleware(middleware: Middleware): Server {
  110. if(middleware.getRoute() != null)
  111. this.instance.use(<string>middleware.getRoute(), middleware.getAction());
  112. else
  113. this.instance.use(middleware.getAction());
  114. return this;
  115. }
  116. public addRoute(route: Route): Server {
  117. if(route.getRoute() == null)
  118. throw new RouteNotSetException();
  119. switch(route.getMethod()) {
  120. case HttpMethod.GET:
  121. return this.get(route);
  122. case HttpMethod.POST:
  123. return this.post(route);
  124. default:
  125. throw new IncorrectMethodException();
  126. }
  127. }
  128. private registerRoutesDocumentation(): Server {
  129. for(const routeName in this.httpHandlers) {
  130. const route = this.httpHandlers[routeName];
  131. if(!(route instanceof Route))
  132. continue;
  133. if(route.getRoute() == null)
  134. throw new RouteNotSetException();
  135. if(![HttpMethod.GET, HttpMethod.POST].includes(route.getMethod()))
  136. throw new IncorrectMethodException();
  137. const docs = route.getDocumentation();
  138. if(this.swaggerDocsPath && docs.length > 0) {
  139. fs.appendFileSync(this.swaggerDocsPath, `${docs}\n`);
  140. this.logInfo(`Swagger documentation for route '${route.getRoute()}' generated!`);
  141. }
  142. }
  143. return this;
  144. }
  145. public registerWsServers(): Server {
  146. for(const url of Object.keys(this.wsHandlers)) {
  147. const wsServer = this.wsServers[url] = new WebSocketServer({ noServer: true });
  148. const wsHandler = this.wsHandlers[url];
  149. wsServer.on(WebSocketHandler.Event.CONNECTION, (ws: WS) => {
  150. wsHandler.onConnect(ws);
  151. ws.on(WebSocketHandler.Event.MESSAGE, wsHandler.onMessage);
  152. ws.on(WebSocketHandler.Event.ERROR, wsHandler.onError);
  153. ws.on(WebSocketHandler.Event.CLOSE, wsHandler.onClose);
  154. });
  155. }
  156. return this;
  157. }
  158. public applyWsHandlers(): Server {
  159. this.httpServer.on('upgrade', (request, socket, head) => {
  160. const url = request.url?.split('?')[0];
  161. if(url && this.wsHandlers[url] && this.wsServers[url]) {
  162. const wsServer = this.wsServers[url];
  163. wsServer.handleUpgrade(request, socket, head, (ws) => {
  164. wsServer.emit(WebSocketHandler.Event.CONNECTION, ws, request);
  165. });
  166. } else {
  167. socket.destroy();
  168. }
  169. });
  170. return this;
  171. }
  172. public getWsConnections(url: string): Set<WS> | null {
  173. const wsServer = this.wsServers[url];
  174. return wsServer ? wsServer.clients : null;
  175. }
  176. public logInfo(message: string): void {
  177. this.logger.getLogger().info(message);
  178. }
  179. public logError(message: string): void {
  180. this.logger.getLogger().error(message);
  181. }
  182. public logWarn(message: string): void {
  183. this.logger.getLogger().warn(message);
  184. }
  185. public log(message: Message): void {
  186. switch(message.type) {
  187. case MessageTypes.WARNING:
  188. return this.logWarn(message.text);
  189. case MessageTypes.ERROR:
  190. return this.logError(message.text);
  191. default:
  192. return this.logInfo(message.text);
  193. }
  194. }
  195. private get(route: Route): Server {
  196. this.instance.get(<string>route.getRoute(), route.getAction());
  197. return this;
  198. }
  199. private post(route: Route): Server {
  200. this.instance.post(<string>route.getRoute(), route.getAction());
  201. return this;
  202. }
  203. private registerSwaggerMiddleware(): Server {
  204. if(!this.swaggerDocsPath)
  205. return this;
  206. const swaggerOptions = {
  207. swaggerDefinition: {
  208. openapi: '3.0.0',
  209. info: {
  210. title: this.swaggerTitle!,
  211. version: this.swaggerApiVersion!,
  212. description: this.swaggerDescription!,
  213. },
  214. servers: [
  215. { url: this.host }
  216. ],
  217. },
  218. apis: [this.swaggerDocsPath],
  219. };
  220. const swaggerDocs = swaggerJsDoc(swaggerOptions);
  221. this.instance.use(this.swaggerRoute!, swaggerUi.serve, swaggerUi.setup(swaggerDocs));
  222. return this;
  223. }
  224. public async registerRoutes(dir: string): Promise<Server> {
  225. const files = fs.readdirSync(dir, { recursive: true, encoding: 'utf8' });
  226. for(const file of files) {
  227. if(/\.js$/.test(file)) {
  228. const {default: RouteClass} = await import(path.join(dir, file));
  229. if(RouteClass.prototype instanceof Route) {
  230. this.httpHandlers[RouteClass.name] = <HttpHandler>new RouteClass(this);
  231. } else throw new InvalidRouteException(file);
  232. }
  233. }
  234. return this;
  235. }
  236. public async registerMiddlewares(dir: string): Promise<Server> {
  237. const files = fs.readdirSync(dir, { recursive: true, encoding: 'utf8' });
  238. for(const file of files) {
  239. if(/\.js$/.test(file)) {
  240. const {default: MiddlewareClass} = await import(path.join(dir, file));
  241. if(MiddlewareClass.prototype instanceof Middleware) {
  242. this.httpHandlers[MiddlewareClass.name] = <HttpHandler>new MiddlewareClass(this);
  243. } else throw new InvalidMiddlewareException(file);
  244. }
  245. }
  246. return this;
  247. }
  248. public getLogger(): Logger {
  249. return this.logger;
  250. }
  251. public i18nLoad(path: string): Server {
  252. this.i18n.load(path);
  253. return this;
  254. }
  255. public getHost(): string {
  256. return this.host;
  257. }
  258. public getOption(key: string): any {
  259. return this.options ? this.options[key] || null : null;
  260. }
  261. public start(callback?: () => any): void {
  262. if(!this.initialized)
  263. throw new ServerNotInitializedException();
  264. this.registerRoutesDocumentation();
  265. this.registerSwaggerMiddleware();
  266. this.processHttpHandlers();
  267. const cb = (): void => {
  268. this.logInfo($$('org.crazydoctor.expressts.start', { 'port': this.port }));
  269. if(callback) callback();
  270. };
  271. this.httpServer.listen(this.port, cb);
  272. }
  273. }
  274. export { Server };