When using the Express router, the usual sequence of events is to detect the route, examine the request, perform some action, then send back the response. It’s quite likely that the action to be performed is asynchronous, so that’s better done with promises than a potentially confusing series of callbacks. I was working on a generic way of handling promises as middleware, and came across this post. I’ve tweaked that a little and here’s the final result.
Handling a route
1 2 3 |
app.get("/:bosskey/:mode", function(req, res) { res.prom(Process.reqGetKey(req)); }); |
1 2 3 4 |
// appengine health check app.get('/_ah/health', function(req, res) { res.prom(Process.ping()); }); |
1 2 3 4 5 6 7 8 9 |
app.get('/info', function(req, res) { res.prom(Promise.resolve({ ok: true, code: 200, info: { api:'effex-api', version:'1.0' }})); }); |
The middleware
1 2 3 4 5 6 7 8 9 10 11 12 |
// this is a middleware to handle promises in the router function prommy(req, res, next) { res.prom = function(prom) { prom.then(function(result) { res.json(result); }) .catch(function(error) { res.json(error); }); }; next(); } |
Using the middleware
For more like this, see React, redux, redis, material-UI and firebase. Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.