Created
February 11, 2018 19:49
-
-
Save Paxa/da339f1f72732bb0ee42d342da9ff6f7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const asyncRouter = require('../lib/async_router'); | |
var router = asyncRouter(express.Router()); | |
router.get('/', async (req, res, next) => { | |
// mkaing async errors | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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