webserver.class.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import express, { Express, NextFunction, Request, Response } from 'express';
  2. import { HttpStatusException } from '../../common/lib/http-status.exception';
  3. import { Logger } from '../../common/util/logger.class';
  4. import { Collector } from './collector.class';
  5. export class Webserver {
  6. private app: Express;
  7. constructor(private port: number, private collector: Collector) {
  8. this.app = express();
  9. this.app.get('/', async (req, res, next) => {
  10. try {
  11. const hdl = await this.collector.trx.start();
  12. if (!hdl) {
  13. return res.send({ hdl: null, data: [] });
  14. }
  15. const data = await this.collector.trx.read();
  16. res.send({
  17. hdl,
  18. data
  19. });
  20. } catch (err) {
  21. next(err);
  22. }
  23. });
  24. this.app.patch('/:hdl', async (req, res, next) => {
  25. try {
  26. const hdl = Number(req.params.hdl);
  27. await this.collector.trx.commit(hdl);
  28. res.send({ ok: true });
  29. } catch (err) {
  30. next(err);
  31. }
  32. });
  33. this.app.delete('/:hdl', async (req, res, next) => {
  34. try {
  35. const hdl = Number(req.params.hdl);
  36. await this.collector.trx.rollback(hdl);
  37. res.send({ ok: true });
  38. } catch (err) {
  39. next(err);
  40. }
  41. });
  42. this.app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  43. if (err instanceof HttpStatusException) {
  44. res.status(err.statusCode).send(err.message);
  45. } else {
  46. Logger.error('[ERROR] Webservice ErrorHandler caught:', err);
  47. res.status(500).send(JSON.stringify(err));
  48. }
  49. });
  50. this.app.listen(this.port, () => {
  51. Logger.info(`[INFO] Monitoring Daemon Webservice started at http://localhost:${this.port}`);
  52. });
  53. }
  54. }