Created
September 16, 2017 20:50
-
-
Save anonymous/2533306da35e38e776e0275646a15ae0 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 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