Server.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 { InvalidMiddlewareException } from '../base/exceptions';
  11. import { InvalidRouteException } from '../base/exceptions';
  12. import { ServerNotInitializedException } from '../base/exceptions';
  13. /** @sealed */
  14. class Server {
  15. private instance: Express;
  16. private readonly port: number;
  17. private readonly logger: Logger;
  18. private i18n: i18nLoader;
  19. public static readonly i18nDefaultPath = '../resources/i18n.json';
  20. public static readonly defaultMiddlewaresPath = '../middlewares';
  21. public static readonly defaultRoutesPath = '../routes';
  22. private readonly httpHandlers: {[key: string]: HttpHandler};
  23. private initialized: boolean;
  24. private readonly i18nPath?: string;
  25. private readonly middlewaresPath?: string;
  26. private readonly routesPath?: string;
  27. private readonly viewEngine?: string;
  28. public constructor(properties: ServerProperties) {
  29. this.instance = express();
  30. this.port = properties.port;
  31. this.i18n = i18nLoader.getInstance();
  32. if(properties.locale)
  33. this.i18n.setLocale(properties.locale);
  34. this.logger = new Logger();
  35. this.httpHandlers = {};
  36. this.i18nPath = properties.i18nPath;
  37. this.middlewaresPath = properties.middlewaresPath;
  38. this.routesPath = properties.routesPath;
  39. this.viewEngine = properties.viewEngine;
  40. this.initialized = false;
  41. }
  42. public async init(): Promise<Server> {
  43. this.i18n.load(path.resolve(__dirname, Server.i18nDefaultPath));
  44. await this.registerMiddlewares(path.resolve(__dirname, Server.defaultMiddlewaresPath));
  45. await this.registerRoutes(path.resolve(__dirname, Server.defaultRoutesPath));
  46. await this.postInit();
  47. this.initialized = true;
  48. return this;
  49. }
  50. private async postInit(): Promise<void> {
  51. if(this.i18nPath)
  52. this.i18n.load(this.i18nPath);
  53. if(this.middlewaresPath)
  54. await this.registerMiddlewares(this.middlewaresPath);
  55. if(this.routesPath)
  56. await this.registerRoutes(this.routesPath);
  57. if(this.viewEngine)
  58. this.instance.set('view engine', this.viewEngine);
  59. }
  60. private processHttpHandlers(): void {
  61. const handlers: HttpHandler[] = [];
  62. for(const key in this.httpHandlers)
  63. handlers.push(this.httpHandlers[key]);
  64. handlers.sort((a, b) => a.getOrder() - b.getOrder());
  65. for(const handler of handlers) {
  66. if(handler instanceof Middleware)
  67. this.addMiddleware(handler);
  68. else if (handler instanceof Route)
  69. this.addRoute(handler);
  70. }
  71. }
  72. public addMiddleware(middleware: Middleware): Server {
  73. if(middleware.getRoute() != null)
  74. this.instance.use(<string>middleware.getRoute(), middleware.getAction());
  75. else
  76. this.instance.use(middleware.getAction());
  77. return this;
  78. }
  79. public addRoute(route: Route): Server {
  80. if(route.getRoute() == null)
  81. throw new RouteNotSetException();
  82. switch(route.getMethod()) {
  83. case HttpMethod.GET:
  84. return this.get(route);
  85. case HttpMethod.POST:
  86. return this.post(route);
  87. default:
  88. throw new IncorrectMethodException();
  89. }
  90. }
  91. public logInfo(message: string): void {
  92. this.logger.getLogger().info(message);
  93. }
  94. public logError(message: string): void {
  95. this.logger.getLogger().error(message);
  96. }
  97. public logWarn(message: string): void {
  98. this.logger.getLogger().warn(message);
  99. }
  100. public log(message: Message): void {
  101. switch(message.type) {
  102. case MessageTypes.WARNING:
  103. return this.logWarn(message.text);
  104. case MessageTypes.ERROR:
  105. return this.logError(message.text);
  106. default:
  107. return this.logInfo(message.text);
  108. }
  109. }
  110. private get(route: Route): Server {
  111. this.instance.get(<string>route.getRoute(), route.getAction());
  112. return this;
  113. }
  114. private post(route: Route): Server {
  115. this.instance.post(<string>route.getRoute(), route.getAction());
  116. return this;
  117. }
  118. public async registerRoutes(dir: string): Promise<Server> {
  119. const files = fs.readdirSync(dir);
  120. for(const file of files) {
  121. if(/\.js$/.test(file)) {
  122. const {default: RouteClass} = await import(path.join(dir, file));
  123. if(RouteClass.prototype instanceof Route) {
  124. this.httpHandlers[RouteClass.name] = <HttpHandler>new RouteClass(this);
  125. } else throw new InvalidRouteException(file);
  126. }
  127. }
  128. return this;
  129. }
  130. public async registerMiddlewares(dir: string): Promise<Server> {
  131. const files = fs.readdirSync(dir);
  132. for(const file of files) {
  133. if(/\.js$/.test(file)) {
  134. const {default: MiddlewareClass} = await import(path.join(dir, file));
  135. if(MiddlewareClass.prototype instanceof Middleware) {
  136. this.httpHandlers[MiddlewareClass.name] = <HttpHandler>new MiddlewareClass(this);
  137. } else throw new InvalidMiddlewareException(file);
  138. }
  139. }
  140. return this;
  141. }
  142. public getLogger(): Logger {
  143. return this.logger;
  144. }
  145. public i18nLoad(path: string): Server {
  146. this.i18n.load(path);
  147. return this;
  148. }
  149. public start(callback?: () => any): void {
  150. if(!this.initialized)
  151. throw new ServerNotInitializedException();
  152. this.processHttpHandlers();
  153. const cb = (): void => {
  154. this.logInfo($$('org.crazydoctor.expressts.start', { 'port': this.port }));
  155. if(callback) callback();
  156. };
  157. this.instance.listen(this.port, cb);
  158. }
  159. }
  160. export { Server };