import { RouterOptions, json } from 'express'; import { HttpStatusException } from '../../../common/lib/http-status.exception'; import { ControllerPool } from '../ctrl/controller-pool.interface'; import { ServiceChangedStatus } from '../ctrl/database.class'; import { WebHandler } from './web-handler.base'; export class ServicesAPIHandler extends WebHandler { constructor(protected ctrlPool: ControllerPool, options?: RouterOptions) { super(ctrlPool, options); this.router.use(json()); this.router.use(this.avoidCache); this.router.get('/:serverID', async (req, res, next) => { try { const serverID = this.validateNumber(req.params.serverID, 'server id'); const services = await this.ctrlPool.db.getHttpCheckConfigs(serverID); res.send(services); } catch (err) { next(err); } }); this.router.put('/:serverID', async (req, res, next) => { try { const serverID = this.validateNumber(req.params.serverID, 'server id'); const result = await this.ctrlPool.db.saveHttpCheckConfig(serverID, req.body); if (result.status !== ServiceChangedStatus.None) { await this.ctrlPool.httpChecks.updateCheck(result.status, result.result); } res.send(result.result); } catch (err) { next(err); } }); this.router.delete('/:serverID/:serviceID', async (req, res, next) => { try { const serverID = this.validateNumber(req.params.serverID, 'server id'); const serviceID = this.validateNumber(req.params.serviceID, 'service id'); const deleted = await this.ctrlPool.db.deleteHealthCheckConfig(serverID, serviceID); if (deleted) { await this.ctrlPool.httpChecks.updateCheck(ServiceChangedStatus.Deactivated, { id: serviceID } as HttpCheckConfig); } res.send({ deleted }); } catch (err) { next(err); } }); } private validateNumber(id: string, field: string) { const num = Number(id); if (Number.isNaN(num)) { throw new HttpStatusException(`Not a valid ${field}: ${id}`, 400); } return num; } }