Skip to content

Instantly share code, notes, and snippets.

@onhate
Last active January 17, 2021 11:24
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 onhate/53ebabb8c390fd0c9404cf9ed9c0f4ee to your computer and use it in GitHub Desktop.
Save onhate/53ebabb8c390fd0c9404cf9ed9c0f4ee to your computer and use it in GitHub Desktop.
Load Express Routes dynamically like Nuxt.js
const express = require('express');
const glob = require("glob");
const app = express();
glob.sync('./api/**/*.http.js', { cwd: __dirname })
.forEach(file => {
const endpoint = file.split('.http.js').join('')
.split('_').join(':')
.substr(1);
app.use(endpoint, require(file));
});
@onhate
Copy link
Author

onhate commented Sep 5, 2019

This small snippet of code converts this file structure:

api
|-- v1
|    |-- users 
|    |    |-- _id
|    |    |    |-- bills
|    |    |    |    |-- _billId.http.js
|    |    |    |-- bills.http.js
|    |    |-- _id.http.js
|    |-- users.http.js

into

/api/v1/users -> users.http.js
/api/v1/users/:id -> _id.http.js
/api/v1/users/:id/bills -> bills.https.js
/api/v1/users/:id/bills/:billId -> _bill.http.js

and a .http.js will look like this, from the file perspective it binds to / as the path to it will be the express route path bind to the router.

const router = require('express').Router();

router.get('/', (req, res) => {
    res.status(200).send('ok');
});

module.exports = router;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment