services-api-handler.class.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { RouterOptions, json } from 'express';
  2. import { HttpStatusException } from '../../../common/lib/http-status.exception';
  3. import { ControllerPool } from '../ctrl/controller-pool.interface';
  4. import { ServiceChangedStatus } from '../ctrl/database.class';
  5. import { WebHandler } from './web-handler.base';
  6. export class ServicesAPIHandler extends WebHandler {
  7. constructor(protected ctrlPool: ControllerPool, options?: RouterOptions) {
  8. super(ctrlPool, options);
  9. this.router.use(json());
  10. this.router.use(this.avoidCache);
  11. this.router.get('/:serverID', async (req, res, next) => {
  12. try {
  13. const serverID = this.validateNumber(req.params.serverID, 'server id');
  14. const services = await this.ctrlPool.db.getHttpCheckConfigs(serverID);
  15. res.send(services);
  16. } catch (err) {
  17. next(err);
  18. }
  19. });
  20. this.router.put('/:serverID', async (req, res, next) => {
  21. try {
  22. const serverID = this.validateNumber(req.params.serverID, 'server id');
  23. const result = await this.ctrlPool.db.saveHttpCheckConfig(serverID, req.body);
  24. if (result.status !== ServiceChangedStatus.None) {
  25. await this.ctrlPool.httpChecks.updateCheck(result.status, result.result);
  26. }
  27. res.send(result.result);
  28. } catch (err) {
  29. next(err);
  30. }
  31. });
  32. this.router.delete('/:serverID/:serviceID', async (req, res, next) => {
  33. try {
  34. const serverID = this.validateNumber(req.params.serverID, 'server id');
  35. const serviceID = this.validateNumber(req.params.serviceID, 'service id');
  36. const deleted = await this.ctrlPool.db.deleteHealthCheckConfig(serverID, serviceID);
  37. if (deleted) {
  38. await this.ctrlPool.httpChecks.updateCheck(ServiceChangedStatus.Deactivated, { id: serviceID } as HttpCheckConfig);
  39. }
  40. res.send({ deleted });
  41. } catch (err) {
  42. next(err);
  43. }
  44. });
  45. }
  46. private validateNumber(id: string, field: string) {
  47. const num = Number(id);
  48. if (Number.isNaN(num)) {
  49. throw new HttpStatusException(`Not a valid ${field}: ${id}`, 400);
  50. }
  51. return num;
  52. }
  53. }