Server.ts 5.7 KB

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