0

I've an expressJS RESTapi project. My folder structure is something like this.

/
/src
 /routes
 /controller
 /models
/app.js

In my routes folder

/routes
 /banners.routes.js
 /reviews.routes.js
 /users.routes.js

banners.routes.js file looks like this

const express = require('express');
    const router = express.Router();
    const passport = require('passport');
    // eslint-disable-next-line no-unused-vars
    const passportConf = require('../../passport');
    const controller = require('../controllers/banner.controller');

    router.post('/', passport.authenticate('jwt', { session: false }), controller.read);

    module.exports = router;

In my app.js file

const banners = require('./src/routes/banners.routes');
const users = require('./src/routes/users.routes');
const reviews = require('./src/routes/reviews.routes');

app.use('/banners', banners);
app.use('/users', users);
app.use('/reviews', reviews);

Now only I've three. If I have 100 different routes, I need to do this 100 times which is very inefficient. There should be a way to automate this.

I go thought the stackoverflow questions and I could found a solution for RESTapis. I created a file called index.js and add this snippet to that

const fs = require('fs');
const path = require('path');
const basename = path.basename(__filename);


fs
  .readdirSync(__dirname)
  .filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))
  .forEach((file) => {
    console.log(file)
  });

This logs all the file names like this.

banners.routes.js
reviews.routes.js
users.routes.js

Is there a way to automate this routing thing?

Hope my question is clear to you.

margherita pizza
  • 6,623
  • 23
  • 84
  • 152
  • Place your code to find the files inside your `app.js` and then build up the `app.use` using this info.. – Keith Jul 12 '19 at 11:34
  • Here's a related question with similar answer to below: https://stackoverflow.com/questions/25623041/how-to-configure-dynamic-routes-with-express-js – Oliver Jul 12 '19 at 11:40

1 Answers1

3

You could dinamically require all files and instanciate all routes assuming you follow some naming convention. For your specific case <name>.routes.js handles /<name> route

const fs = require('fs');
const path = require('path');
const POSTFIX = '.routes.js'

// generate [[name, handler]] pairs
module.exports = fs
  .readdirSync(__dirname)
  .filter(file => file.endsWith(POSTFIX))
  .map(file => [path.basename(file, POSTFIX), require(`./${file}`)]);

And then in app.js

const routes = require('./src/routes')

routes.forEach(([name, handler]) => app.use(`/${name}`, handler))
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • @PareshBarad What do you mean by "every time"? This would only run once during application startup process. Require will only load file once during run time unless you manually clean require cache. – Yury Tarabanko Jul 12 '19 at 12:06