Skip to content

Instantly share code, notes, and snippets.

Created September 16, 2017 20:50
Show Gist options
  • Save anonymous/2533306da35e38e776e0275646a15ae0 to your computer and use it in GitHub Desktop.
Save anonymous/2533306da35e38e776e0275646a15ae0 to your computer and use it in GitHub Desktop.
const Boom = require('boom')
/**
* call a middleware
* @method tryCatch
* @param {Function} fn
* @return {Promise}
*/
const tryCatch = fn => {
try {
return Promise.resolve(fn())
} catch (e) {
return Promise.reject(e)
}
}
/**
* @method sendError
* @param {ResponseRestify} res response instance
* @param {Error} e
*/
const sendError = (res, e) => {
const output = Boom.boomify(e).output
res.send(output.statusCode, output)
}
/**
* @method wrapMiddleware
* @param {Function} middleware route middleware
* @return {Function}
*/
const wrapMiddleware = middleware => {
return (req, res) => {
const handler = () => middleware(req, res)
tryCatch(handler)
.then(result => {
res.json(result)
})
.catch(sendError)
}
}
module.exports = wrapMiddleware
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment