Server.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 exceptions_3 = require("../base/exceptions");
  48. const exceptions_4 = require("../base/exceptions");
  49. const exceptions_5 = require("../base/exceptions");
  50. /** @sealed */
  51. class Server {
  52. constructor(properties) {
  53. this.instance = (0, express_1.default)();
  54. this.port = properties.port;
  55. this.i18n = i18n_1.i18nLoader.getInstance().setLocale(properties.locale);
  56. this.logger = new logger_1.Logger();
  57. this.httpHandlers = {};
  58. this.i18nPath = properties.i18nPath;
  59. this.middlewaresPath = properties.middlewaresPath;
  60. this.routesPath = properties.routesPath;
  61. this.initialized = false;
  62. }
  63. init() {
  64. return __awaiter(this, void 0, void 0, function* () {
  65. this.i18n.load(path_1.default.resolve(__dirname, Server.i18nDefaultPath));
  66. yield this.registerMiddlewares(path_1.default.resolve(__dirname, Server.defaultMiddlewaresPath));
  67. yield this.registerRoutes(path_1.default.resolve(__dirname, Server.defaultRoutesPath));
  68. yield this.postInit();
  69. this.initialized = true;
  70. return this;
  71. });
  72. }
  73. postInit() {
  74. return __awaiter(this, void 0, void 0, function* () {
  75. if (this.i18nPath)
  76. this.i18n.load(this.i18nPath);
  77. if (this.middlewaresPath)
  78. yield this.registerMiddlewares(this.middlewaresPath);
  79. if (this.routesPath)
  80. yield this.registerRoutes(this.routesPath);
  81. });
  82. }
  83. processHttpHandlers() {
  84. const handlers = [];
  85. for (const key in this.httpHandlers)
  86. handlers.push(this.httpHandlers[key]);
  87. handlers.sort((a, b) => a.getOrder() - b.getOrder());
  88. for (const handler of handlers) {
  89. if (handler instanceof http_1.Middleware)
  90. this.addMiddleware(handler);
  91. else if (handler instanceof http_1.Route)
  92. this.addRoute(handler);
  93. }
  94. }
  95. addMiddleware(middleware) {
  96. if (middleware.getRoute() != null)
  97. this.instance.use(middleware.getRoute(), middleware.getAction());
  98. else
  99. this.instance.use(middleware.getAction());
  100. return this;
  101. }
  102. addRoute(route) {
  103. if (route.getRoute() == null)
  104. throw new exceptions_1.RouteNotSetException();
  105. switch (route.getMethod()) {
  106. case http_1.HttpMethod.GET:
  107. return this.get(route);
  108. case http_1.HttpMethod.POST:
  109. return this.post(route);
  110. default:
  111. throw new exceptions_2.IncorrectMethodException();
  112. }
  113. }
  114. logInfo(message) {
  115. this.logger.getLogger().info(message);
  116. }
  117. logError(message) {
  118. this.logger.getLogger().error(message);
  119. }
  120. logWarn(message) {
  121. this.logger.getLogger().warn(message);
  122. }
  123. log(message) {
  124. switch (message.type) {
  125. case logger_1.MessageTypes.WARNING:
  126. return this.logWarn(message.text);
  127. case logger_1.MessageTypes.ERROR:
  128. return this.logError(message.text);
  129. default:
  130. return this.logInfo(message.text);
  131. }
  132. }
  133. get(route) {
  134. this.instance.get(route.getRoute(), route.getAction());
  135. return this;
  136. }
  137. post(route) {
  138. this.instance.post(route.getRoute(), route.getAction());
  139. return this;
  140. }
  141. registerRoutes(dir) {
  142. return __awaiter(this, void 0, void 0, function* () {
  143. const files = fs_1.default.readdirSync(dir);
  144. for (const file of files) {
  145. if (/\.(ts|js)$/.test(file)) {
  146. const { default: RouteClass } = yield Promise.resolve(`${path_1.default.join(dir, file)}`).then(s => __importStar(require(s)));
  147. if (RouteClass.prototype instanceof http_1.Route) {
  148. this.httpHandlers[RouteClass.name] = new RouteClass(this);
  149. }
  150. else
  151. throw new exceptions_4.InvalidRouteException(file);
  152. }
  153. }
  154. return this;
  155. });
  156. }
  157. registerMiddlewares(dir) {
  158. return __awaiter(this, void 0, void 0, function* () {
  159. const files = fs_1.default.readdirSync(dir);
  160. for (const file of files) {
  161. if (/\.(ts|js)$/.test(file)) {
  162. const { default: MiddlewareClass } = yield Promise.resolve(`${path_1.default.join(dir, file)}`).then(s => __importStar(require(s)));
  163. if (MiddlewareClass.prototype instanceof http_1.Middleware) {
  164. this.httpHandlers[MiddlewareClass.name] = new MiddlewareClass(this);
  165. }
  166. else
  167. throw new exceptions_3.InvalidMiddlewareException(file);
  168. }
  169. }
  170. return this;
  171. });
  172. }
  173. getLogger() {
  174. return this.logger;
  175. }
  176. i18nLoad(path) {
  177. this.i18n.load(path);
  178. return this;
  179. }
  180. start(callback) {
  181. if (!this.initialized)
  182. throw new exceptions_5.ServerNotInitializedException();
  183. this.processHttpHandlers();
  184. const cb = () => {
  185. this.logInfo((0, i18n_1.$$)('org.crazydoctor.expressts.start', { 'port': this.port }));
  186. if (callback)
  187. callback();
  188. };
  189. this.instance.listen(this.port, cb);
  190. }
  191. }
  192. exports.Server = Server;
  193. Server.i18nDefaultPath = '../resources/i18n.json';
  194. Server.defaultMiddlewaresPath = '../middlewares';
  195. Server.defaultRoutesPath = '../routes';