Created
March 10, 2019 08:51
-
-
Save VanDalkvist/1da00170629cb6d27a8c2b778a13f1d9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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