Created
March 29, 2020 15:45
-
-
Save Wyru/926a7bddd6aed7d196a3148650058463 to your computer and use it in GitHub Desktop.
Dynamically loads routes for express
This file contains 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
// Examples | |
// "routes/get.js" for a get on "/" | |
// "route/users/get.js" for a get on "/users" | |
// "route/users/post.js" for a post on "/users" | |
// "route/users/$id/post.js" for a post on "/users/:id" | |
import fs from 'fs-readdir-recursive' | |
import express from 'express' | |
const router = express.Router(); | |
const routesLoader = (app) => { | |
const routes = fs(`${__dirname}/../routes`); | |
routes.forEach((route) => { | |
route = route.replace(/\\/g, '/'); | |
let paths = route.split('/') | |
let action = paths.pop(); | |
action = action.slice(0, -3); | |
let url = paths.reduce((acc, cur) => `${acc}/${cur}` | |
, ''); | |
let actionPath = `../routes/${url}/${action}`; | |
actionPath = actionPath.replace(/\/\//g, '/'); | |
url = url.replace(/\$/g, ':'); | |
router[action](url, require(actionPath).default); | |
}) | |
app.use(router); | |
} | |
export default routesLoader; |
This file contains 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
import express from 'express'; | |
import utils from './utils'; | |
const app = express(); | |
utils.routesLoader(app); | |
app.listen(33333, () => { | |
console.log('listen port 33333'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment