Server.ts 5.2 KB

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