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.