Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Helper to use promises in restify (might also work for express)
/**
* Use restify with promises
*
* Restify middleware and route handlers are passed a callback function `next`
* which must be called on success, or on an error.
*
* But you may prefer to define your middleware and routes using promises or
* async functions instead of using callbacks.
*
* To achieve that, simply wrap your middleware functions in `middleware()` and
* your route handlers in `controller()`
*
* Your functions can work with promises, while `middleware()` and
* `controller()` will return a callback-style function which restify can use.
*
* Caveat:
*
* The implementation below assumes that your route handlers will return an
* object, which will be sent to the client as JSON.
*
* If you want to be able to send a raw file to the client, e.g. by
* returning Buffer, then the implementation will need to be expanded.
*
* Example usage:
*
* const { middleware, controller } = require('./helpers/asyncWrappers');
*
* server.get(
* { path: '/users/_self', version: VERSION },
* // We simply wrap our middleware and handler functions here
* middleware(authUserMiddleware),
* controller(getUserSelf)
* );
*
* // Now we can use async or promise-returning functions
*
* async function authUserMiddleware(req) {
* const authToken = req.headers['x-auth-token'];
* const user = await authHelper.findUserFromToken(authToken);
* if (!user) throw Error("No user found!");
* });
*
* function getUserSelf() {
* return Promise.resolve({
* name: 'Example User',
* color: 'green'
* });
* }
*
*/
// Implementation
// We use Promise.resolve() in both functions, before calling the provided
// handler(), so that just in case the handler() throw a _synchronous_ error,
// we will catch it.
module.exports = {
middleware: (handler) => {
return (req, res, next) => {
Promise.resolve().then(
() => handler(req)
).then(next, next);
};
},
controller: (handler) => {
return (req, res, next) => {
Promise.resolve().then(
() => handler(req)
).then(
result => {
res.json(200, result);
next();
},
error => {
next(error);
}
);
};
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.