|
| 1 | +/* |
| 2 | +Copyright 2020 Javier Brea |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at |
| 5 | +
|
| 6 | +http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +
|
| 8 | +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |
| 9 | +*/ |
| 10 | + |
| 11 | +"use strict"; |
| 12 | + |
| 13 | +const express = require("express"); |
| 14 | +const Boom = require("@hapi/boom"); |
| 15 | + |
| 16 | +const { PLUGIN_NAME } = require("./constants"); |
| 17 | + |
| 18 | +class AlertsApi { |
| 19 | + constructor(core) { |
| 20 | + this._core = core; |
| 21 | + this._tracer = core.tracer; |
| 22 | + this._alerts = this._core.alerts; |
| 23 | + this._router = express.Router(); |
| 24 | + this._router.get("/", this.getCollection.bind(this)); |
| 25 | + this._router.get("/:id", this.getModel.bind(this)); |
| 26 | + } |
| 27 | + |
| 28 | + _parseModel(alert) { |
| 29 | + return { |
| 30 | + id: alert.context, |
| 31 | + context: alert.context, |
| 32 | + message: alert.message, |
| 33 | + error: alert.error |
| 34 | + ? { |
| 35 | + name: alert.error.name, |
| 36 | + message: alert.error.message, |
| 37 | + stack: alert.error.stack, |
| 38 | + fileName: alert.error.fileName, |
| 39 | + lineNumber: alert.error.lineNumber, |
| 40 | + columnNumber: alert.error.columnNumber, |
| 41 | + } |
| 42 | + : null, |
| 43 | + }; |
| 44 | + } |
| 45 | + |
| 46 | + _parseCollection() { |
| 47 | + return this._alerts.map(this._parseModel); |
| 48 | + } |
| 49 | + |
| 50 | + getCollection(req, res) { |
| 51 | + this._tracer.verbose(`${PLUGIN_NAME}: Sending alerts | ${req.id}`); |
| 52 | + res.status(200); |
| 53 | + res.send(this._parseCollection()); |
| 54 | + } |
| 55 | + |
| 56 | + getModel(req, res, next) { |
| 57 | + const id = req.params.id; |
| 58 | + this._tracer.verbose(`${PLUGIN_NAME}: Sending alert ${id} | ${req.id}`); |
| 59 | + const foundAlert = this._alerts.find((alert) => alert.context === id); |
| 60 | + if (foundAlert) { |
| 61 | + res.status(200); |
| 62 | + res.send(this._parseModel(foundAlert)); |
| 63 | + } else { |
| 64 | + next(Boom.notFound(`Alert with id "${id}" was not found`)); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + get router() { |
| 69 | + return this._router; |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +module.exports = AlertsApi; |
0 commit comments