| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- import express, { Express } from 'express';
- import { HttpStatusException } from '../../common/lib/http-status.exception';
- import { Logger } from '../../common/util/logger.class';
- import { Database } from './database.class';
- export class Webserver {
- private app: Express;
- constructor(private port: number, private db: Database) {
- this.app = express();
- this.app.get('/server', async (req, res, next) => {
- try {
- const serverConfigs = await this.db.getAllServerConfigs();
- res.send(serverConfigs);
- } catch (err) {
- next(err);
- }
- });
- this.app.get('/server/:serverID/data/types', async (req, res, next) => {
- try {
- const serverID = Number(req.params.serverID);
- if (Number.isNaN(serverID)) {
- throw new HttpStatusException(`Not a valid server id: ${req.params.serverID}`, 400);
- }
- const serverDataTypes = await this.db.getServerDataTypes(serverID);
- res.send(serverDataTypes);
- } catch (err) {
- next(err);
- }
- });
- this.app.get('/server/:serverID/data', async (req, res, next) => {
- try {
- const serverID = Number(req.params.serverID);
- if (Number.isNaN(serverID)) {
- throw new HttpStatusException(`Not a valid server id: ${req.params.serverID}`, 400);
- }
- const qStart = (req.query.start || '').toString();
- const qEnd = (req.query.end || '').toString();
- const qType = (req.query.type || '').toString();
- if (!qStart || !qEnd || !qType) throw new HttpStatusException("QueryParams 'type', 'start' and 'end' are mandatory.", 400);
- const start = new Date(qStart);
- const end = new Date(qEnd);
- if ([start.toString(), end.toString()].includes('Invalid Date')) {
- throw new HttpStatusException("QueryParams 'start' and 'end' must be parseable dates or unix epoch timestamps (ms).", 400);
- }
- const data = await this.db.queryServerData(serverID, qType, start, end);
- res.send({
- start,
- end,
- data
- } as QueryResponse<ServerData>);
- } catch (err) {
- next(err);
- }
- });
- this.app.use('/', express.static(process.env.STATIC_DIR || 'public'));
- this.app.use((err, req, res, next) => {
- if (err instanceof HttpStatusException) {
- res.status(err.statusCode).send(err.message);
- } else {
- Logger.error('[ERROR] Webservice ErrorHandler caught:', err);
- res.status(500).send(JSON.stringify(err));
- }
- });
- this.app.listen(this.port, () => {
- Logger.info(`[INFO] Monitoring Webserver started at http://localhost:${this.port}`);
- });
- }
- }
|