class ApiRoutes { constructor(logger, notificationFacade, config) { this.logger = logger; this.notificationFacade = notificationFacade; this.authToken = config.authToken; } create(express) { const router = express.Router(); router.post('/notification', (req, res) => this._wrapAsyncHandler(req, res, this._handlePostNotification.bind(this))); router.post('/notification/reset', (req, res) => this._wrapAsyncHandler(req, res, this._handleResetNotification.bind(this))); return router; } async _handlePostNotification(req, res) { if (req.headers.authorization !== 'Bearer ' + this.authToken) { this._logRequestWarning(req, 'Missing or invalid authorization header'); res.sendStatus(401); return; } if (!req.body || !req.body.subject || !req.body.message) { this._logRequestWarning(req, 'Missing body, subject and/or message parameters'); res.sendStatus(400); return; } await this.notificationFacade.postNotification(req.body.subject, req.body.message, req.body.priority || 0); res.sendStatus(200); } async _handleResetNotification(req, res) { if (!req.body || !req.body.token) { this._logRequestWarning(req, 'Missing token'); res.sendStatus(400); return; } await this.notificationFacade.resetNotification(req.body.token); res.sendStatus(200); } async _wrapAsyncHandler(req, res, handler) { try { await handler(req, res); } catch (err) { this.logger.error(`Unhandled exception in request handler: ${err}`); this.logger.verbose(err.stack); res.sendStatus(500); } } _logRequestWarning(req, message) { this.logger.warn(`[${req.ip}] ${message}`); } } module.exports = ApiRoutes;