Skip to content

Instantly share code, notes, and snippets.

@VanDalkvist
Created March 10, 2019 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VanDalkvist/1da00170629cb6d27a8c2b778a13f1d9 to your computer and use it in GitHub Desktop.
Save VanDalkvist/1da00170629cb6d27a8c2b778a13f1d9 to your computer and use it in GitHub Desktop.
const express = require("express");
module.exports = (app, { base = "" } = {}) => ({
applyApi: api => app.use(base + api.base, buildRouter(api)),
applyRoute: route => applyRoute(app, { base })(route),
applyMiddleware: middleware => app.use(awaitHandlerFactory(middleware))
});
function buildRouter(api) {
const routeReducer = (router, key) => applyRoute(router)(api.methods[key]);
return Object.keys(api.methods).reduce(routeReducer, express.Router());
}
function applyRoute(app, { base = "" } = {}) {
return route => {
app[route.method.toLowerCase()](base + route.path, awaitHandlerFactory(route.handler));
return app;
};
}
function awaitHandlerFactory(middleware) {
return async (req, res, next) => {
try {
await middleware(req, res, next);
} catch (err) {
next(err);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment