Skip to content

Instantly share code, notes, and snippets.

@Paxa
Created February 11, 2018 19:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Paxa/da339f1f72732bb0ee42d342da9ff6f7 to your computer and use it in GitHub Desktop.
Save Paxa/da339f1f72732bb0ee42d342da9ff6f7 to your computer and use it in GitHub Desktop.
const express = require('express');
const asyncRouter = require('../lib/async_router');
var router = asyncRouter(express.Router());
router.get('/', async (req, res, next) => {
// mkaing async errors
});
const methods = require('methods');
const catchAsyncErrors = (fn) => {
return (req, res, next) => {
const routePromise = fn(req, res, next);
if (routePromise && routePromise.catch) {
routePromise.catch(err => {
next(err)
});
}
}
}
const flatten = (list) => {
return list.reduce((a, b) => {
return a.concat(Array.isArray(b) ? flatten(b) : b);
}, []);
};
const slice = Array.prototype.slice;
var asyncRouter = (router) => {
methods.concat('all').forEach(method => {
var original = router[method];
router[method] = function (path) {
var handles = flatten(slice.call(arguments, 1));
var patched = [];
handles.forEach(handle => {
if (typeof handle !== 'function') {
var type = toString.call(handle);
var msg = 'Route.all() requires a callback function but got a ' + type
throw new TypeError(msg);
}
patched.push(catchAsyncErrors(handle));
});
original.call(this, path, patched);
}
});
return router;
};
module.exports = asyncRouter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment