Server.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. var desc = Object.getOwnPropertyDescriptor(m, k);
  5. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6. desc = { enumerable: true, get: function() { return m[k]; } };
  7. }
  8. Object.defineProperty(o, k2, desc);
  9. }) : (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. o[k2] = m[k];
  12. }));
  13. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15. }) : function(o, v) {
  16. o["default"] = v;
  17. });
  18. var __importStar = (this && this.__importStar) || function (mod) {
  19. if (mod && mod.__esModule) return mod;
  20. var result = {};
  21. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  22. __setModuleDefault(result, mod);
  23. return result;
  24. };
  25. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  26. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  27. return new (P || (P = Promise))(function (resolve, reject) {
  28. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  29. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  30. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  31. step((generator = generator.apply(thisArg, _arguments || [])).next());
  32. });
  33. };
  34. var __importDefault = (this && this.__importDefault) || function (mod) {
  35. return (mod && mod.__esModule) ? mod : { "default": mod };
  36. };
  37. Object.defineProperty(exports, "__esModule", { value: true });
  38. exports.Server = void 0;
  39. const express_1 = __importDefault(require("express"));
  40. const http_1 = require("../base/http");
  41. const exceptions_1 = require("../base/exceptions");
  42. const exceptions_2 = require("../base/exceptions");
  43. const logger_1 = require("../base/logger");
  44. const i18n_1 = require("../base/i18n");
  45. const path_1 = __importDefault(require("path"));
  46. const fs_1 = __importDefault(require("fs"));
  47. const http_2 = __importDefault(require("http"));
  48. const ws_1 = require("ws");
  49. const exceptions_3 = require("../base/exceptions");
  50. const exceptions_4 = require("../base/exceptions");
  51. const exceptions_5 = require("../base/exceptions");
  52. const websocket_1 = require("../base/websocket");
  53. /** @sealed */
  54. class Server {
  55. constructor(properties) {
  56. this.instance = (0, express_1.default)();
  57. this.httpServer = http_2.default.createServer(this.instance);
  58. this.port = properties.port;
  59. this.i18n = i18n_1.i18nLoader.getInstance();
  60. if (properties.locale)
  61. this.i18n.setLocale(properties.locale);
  62. this.logger = new logger_1.Logger();
  63. this.httpHandlers = {};
  64. this.wsHandlers = properties.wsHandlers || {};
  65. this.wsServers = {};
  66. this.i18nPath = properties.i18nPath;
  67. this.middlewaresPath = properties.middlewaresPath;
  68. this.routesPath = properties.routesPath;
  69. this.viewEngine = properties.viewEngine;
  70. this.viewsPath = properties.viewsPath;
  71. this.options = properties.options;
  72. this.initialized = false;
  73. }
  74. init() {
  75. return __awaiter(this, void 0, void 0, function* () {
  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_1.default.resolve(__dirname, Server.i18nDefaultPath));
  81. yield this.registerMiddlewares(path_1.default.resolve(__dirname, Server.defaultMiddlewaresPath));
  82. yield this.registerRoutes(path_1.default.resolve(__dirname, Server.defaultRoutesPath));
  83. yield this.postInit();
  84. this.initialized = true;
  85. return this;
  86. });
  87. }
  88. postInit() {
  89. return __awaiter(this, void 0, void 0, function* () {
  90. if (this.i18nPath)
  91. this.i18n.load(this.i18nPath);
  92. if (this.middlewaresPath)
  93. yield this.registerMiddlewares(this.middlewaresPath);
  94. if (this.routesPath)
  95. yield this.registerRoutes(this.routesPath);
  96. if (Object.keys(this.wsHandlers).length > 0) {
  97. this.registerWsServers();
  98. this.applyWsHandlers();
  99. }
  100. });
  101. }
  102. processHttpHandlers() {
  103. const handlers = [];
  104. for (const key in this.httpHandlers)
  105. handlers.push(this.httpHandlers[key]);
  106. handlers.sort((a, b) => a.getOrder() - b.getOrder());
  107. for (const handler of handlers) {
  108. if (handler instanceof http_1.Middleware)
  109. this.addMiddleware(handler);
  110. else if (handler instanceof http_1.Route)
  111. this.addRoute(handler);
  112. }
  113. }
  114. addMiddleware(middleware) {
  115. if (middleware.getRoute() != null)
  116. this.instance.use(middleware.getRoute(), middleware.getAction());
  117. else
  118. this.instance.use(middleware.getAction());
  119. return this;
  120. }
  121. addRoute(route) {
  122. if (route.getRoute() == null)
  123. throw new exceptions_1.RouteNotSetException();
  124. switch (route.getMethod()) {
  125. case http_1.HttpMethod.GET:
  126. return this.get(route);
  127. case http_1.HttpMethod.POST:
  128. return this.post(route);
  129. default:
  130. throw new exceptions_2.IncorrectMethodException();
  131. }
  132. }
  133. registerWsServers() {
  134. for (const url of Object.keys(this.wsHandlers)) {
  135. const wsServer = this.wsServers[url] = new ws_1.Server({ noServer: true });
  136. const wsHandler = this.wsHandlers[url];
  137. wsServer.on(websocket_1.WebSocketHandler.Event.CONNECTION, (ws) => {
  138. wsHandler.onConnect(ws);
  139. ws.on(websocket_1.WebSocketHandler.Event.MESSAGE, wsHandler.onMessage);
  140. ws.on(websocket_1.WebSocketHandler.Event.ERROR, wsHandler.onError);
  141. ws.on(websocket_1.WebSocketHandler.Event.CLOSE, wsHandler.onClose);
  142. });
  143. }
  144. return this;
  145. }
  146. applyWsHandlers() {
  147. this.httpServer.on('upgrade', (request, socket, head) => {
  148. var _a;
  149. const url = (_a = request.url) === null || _a === void 0 ? void 0 : _a.split('?')[0];
  150. if (url && this.wsHandlers[url] && this.wsServers[url]) {
  151. const wsServer = this.wsServers[url];
  152. wsServer.handleUpgrade(request, socket, head, (ws) => {
  153. wsServer.emit(websocket_1.WebSocketHandler.Event.CONNECTION, ws, request);
  154. });
  155. }
  156. else {
  157. socket.destroy();
  158. }
  159. });
  160. return this;
  161. }
  162. getWsConnections(url) {
  163. const wsServer = this.wsServers[url];
  164. return wsServer ? wsServer.clients : null;
  165. }
  166. logInfo(message) {
  167. this.logger.getLogger().info(message);
  168. }
  169. logError(message) {
  170. this.logger.getLogger().error(message);
  171. }
  172. logWarn(message) {
  173. this.logger.getLogger().warn(message);
  174. }
  175. log(message) {
  176. switch (message.type) {
  177. case logger_1.MessageTypes.WARNING:
  178. return this.logWarn(message.text);
  179. case logger_1.MessageTypes.ERROR:
  180. return this.logError(message.text);
  181. default:
  182. return this.logInfo(message.text);
  183. }
  184. }
  185. get(route) {
  186. this.instance.get(route.getRoute(), route.getAction());
  187. return this;
  188. }
  189. post(route) {
  190. this.instance.post(route.getRoute(), route.getAction());
  191. return this;
  192. }
  193. registerRoutes(dir) {
  194. return __awaiter(this, void 0, void 0, function* () {
  195. const files = fs_1.default.readdirSync(dir);
  196. for (const file of files) {
  197. if (/\.js$/.test(file)) {
  198. const { default: RouteClass } = yield Promise.resolve(`${path_1.default.join(dir, file)}`).then(s => __importStar(require(s)));
  199. if (RouteClass.prototype instanceof http_1.Route) {
  200. this.httpHandlers[RouteClass.name] = new RouteClass(this);
  201. }
  202. else
  203. throw new exceptions_4.InvalidRouteException(file);
  204. }
  205. }
  206. return this;
  207. });
  208. }
  209. registerMiddlewares(dir) {
  210. return __awaiter(this, void 0, void 0, function* () {
  211. const files = fs_1.default.readdirSync(dir);
  212. for (const file of files) {
  213. if (/\.js$/.test(file)) {
  214. const { default: MiddlewareClass } = yield Promise.resolve(`${path_1.default.join(dir, file)}`).then(s => __importStar(require(s)));
  215. if (MiddlewareClass.prototype instanceof http_1.Middleware) {
  216. this.httpHandlers[MiddlewareClass.name] = new MiddlewareClass(this);
  217. }
  218. else
  219. throw new exceptions_3.InvalidMiddlewareException(file);
  220. }
  221. }
  222. return this;
  223. });
  224. }
  225. getLogger() {
  226. return this.logger;
  227. }
  228. i18nLoad(path) {
  229. this.i18n.load(path);
  230. return this;
  231. }
  232. getOption(key) {
  233. return this.options ? this.options[key] || null : null;
  234. }
  235. start(callback) {
  236. if (!this.initialized)
  237. throw new exceptions_5.ServerNotInitializedException();
  238. this.processHttpHandlers();
  239. const cb = () => {
  240. this.logInfo((0, i18n_1.$$)('org.crazydoctor.expressts.start', { 'port': this.port }));
  241. if (callback)
  242. callback();
  243. };
  244. this.httpServer.listen(this.port, cb);
  245. }
  246. }
  247. exports.Server = Server;
  248. Server.i18nDefaultPath = '../resources/i18n.json';
  249. Server.defaultMiddlewaresPath = '../middlewares';
  250. Server.defaultRoutesPath = '../routes';
  251. //# sourceMappingURL=Server.js.map