Server.ts 5.5 KB

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