webserver.class.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import express, { Express } from 'express';
  2. import { HttpStatusException } from '../../common/lib/http-status.exception';
  3. import { Logger } from '../../common/util/logger.class';
  4. import { Database } from './database.class';
  5. export class Webserver {
  6. private app: Express;
  7. constructor(private port: number, private db: Database) {
  8. this.app = express();
  9. this.app.get('/server', async (req, res, next) => {
  10. try {
  11. const serverConfigs = await this.db.getAllServerConfigs();
  12. res.send(serverConfigs);
  13. } catch (err) {
  14. next(err);
  15. }
  16. });
  17. this.app.get('/server/:serverID/data/types', async (req, res, next) => {
  18. try {
  19. const serverID = Number(req.params.serverID);
  20. if (Number.isNaN(serverID)) {
  21. throw new HttpStatusException(`Not a valid server id: ${req.params.serverID}`, 400);
  22. }
  23. const serverDataTypes = await this.db.getServerDataTypes(serverID);
  24. res.send(serverDataTypes);
  25. } catch (err) {
  26. next(err);
  27. }
  28. });
  29. this.app.get('/server/:serverID/data', async (req, res, next) => {
  30. try {
  31. const serverID = Number(req.params.serverID);
  32. if (Number.isNaN(serverID)) {
  33. throw new HttpStatusException(`Not a valid server id: ${req.params.serverID}`, 400);
  34. }
  35. const qStart = (req.query.start || '').toString();
  36. const qEnd = (req.query.end || '').toString();
  37. const qType = (req.query.type || '').toString();
  38. if (!qStart || !qEnd || !qType) throw new HttpStatusException("QueryParams 'type', 'start' and 'end' are mandatory.", 400);
  39. const start = new Date(qStart);
  40. const end = new Date(qEnd);
  41. if ([start.toString(), end.toString()].includes('Invalid Date')) {
  42. throw new HttpStatusException("QueryParams 'start' and 'end' must be parseable dates or unix epoch timestamps (ms).", 400);
  43. }
  44. const data = await this.db.queryServerData(serverID, qType, start, end);
  45. res.send({
  46. start,
  47. end,
  48. data
  49. } as QueryResponse<ServerData>);
  50. } catch (err) {
  51. next(err);
  52. }
  53. });
  54. this.app.use('/', express.static(process.env.STATIC_DIR || 'public'));
  55. this.app.use((err, req, res, next) => {
  56. if (err instanceof HttpStatusException) {
  57. res.status(err.statusCode).send(err.message);
  58. } else {
  59. Logger.error('[ERROR] Webservice ErrorHandler caught:', err);
  60. res.status(500).send(JSON.stringify(err));
  61. }
  62. });
  63. this.app.listen(this.port, () => {
  64. Logger.info(`[INFO] Monitoring Webserver started at http://localhost:${this.port}`);
  65. });
  66. }
  67. }