mailtrain/lib/router-async.js
Tomas Bures 79ea9e1897 Work in progress on a React-based error reporting mechanism.
The idea is that REST handlers always fail with throwing an Error (subclass of InteroperableError). The InteroperableError contains type and data field which are JSON-serialized and sent to client. It's up to the client to interpret the error and choose an appropriate way to present it.
2017-06-05 00:52:59 +02:00

38 lines
1,000 B
JavaScript

'use strict';
const express = require('express');
function safeAsyncHandler(handler) {
return function(req, res, next) {
handler(req, res).catch(error => next(error));
};
}
function replaceLast(elems, replaceFn) {
if (elems.length === 0) {
return elems;
}
const lastElem = elems[elems.size - 1];
const replacement = replaceFn(lastElem);
elems[elems.size - 1] = replacement;
return elems;
}
function create() {
const router = new express.Router();
router.getAsync = (path, ...handlers) => router.get(path, ...replaceLast(handlers, safeAsyncHandler));
router.postAsync = (path, ...handlers) => router.post(path, ...replaceLast(handlers, safeAsyncHandler));
router.putAsync = (path, ...handlers) => router.put(path, ...replaceLast(handlers, safeAsyncHandler));
router.deleteAsync = (path, ...handlers) => router.delete(path, ...replaceLast(handlers, safeAsyncHandler));
return router;
}
module.exports = {
create
};