Server.js 8.3 KB

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