Skip to content

Instantly share code, notes, and snippets.

@martypdx
Created November 12, 2017 17:38
Show Gist options
  • Save martypdx/e36eab1aedf4dbf75a72c9d2a9eec568 to your computer and use it in GitHub Desktop.
Save martypdx/e36eab1aedf4dbf75a72c9d2a9eec568 to your computer and use it in GitHub Desktop.
A helper function for promise returning express middleware
// Assumes:
// 1. application/json response content type
// 2. registered error handler capable of handling rejections
module.exports = function respond(handler) {
return async (req, res, next) => {
try {
const result = await handler(req);
res.json(result);
}
catch(err) {
next(err);
}
};
};
@martypdx
Copy link
Author

martypdx commented Nov 12, 2017

Use in express routes like:

.post('/', respond(async req => {
    //... async/await workflow here
}));

Can be used with simple Promise returning middleware without async:

.post('/', respond(req => Model.save(req.body)));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment