webserver.class.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import express, { Express, NextFunction, Request, Response } from 'express';
  2. import path from 'path';
  3. import { HttpStatusException } from '../../common/lib/http-status.exception';
  4. import { Logger } from '../../common/util/logger.class';
  5. import { ControllerPool } from './ctrl/controller-pool.interface';
  6. import { ServerAPIHandler } from './webhdl/server-api-handler.class';
  7. import { ServicesAPIHandler } from './webhdl/services-api-handler.class';
  8. export class Webserver {
  9. private app: Express;
  10. constructor(private port: number, ctrlPool: ControllerPool) {
  11. this.app = express();
  12. const serverApi = new ServerAPIHandler(ctrlPool);
  13. this.app.use('/server', serverApi.router);
  14. const servicesApi = new ServicesAPIHandler(ctrlPool);
  15. this.app.use('/services', servicesApi.router);
  16. this.app.use('/', express.static(process.env.STATIC_DIR || 'public'));
  17. this.app.use('**', express.static(path.join(process.env.STATIC_DIR || 'public', 'index.html')));
  18. this.app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  19. if (err instanceof HttpStatusException) {
  20. res.status(err.statusCode).send(err.message);
  21. } else {
  22. Logger.error('[ERROR] Webservice ErrorHandler caught:', err);
  23. res.status(500).send(JSON.stringify(err));
  24. }
  25. });
  26. this.app.listen(this.port, () => {
  27. Logger.info(`[INFO] Monitoring Webserver started at http://localhost:${this.port}`);
  28. });
  29. }
  30. }