Server.ts 5.2 KB

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