I am making a new clean structure of nodejs (express) application.
I have a models folder with mongoose schemas, a routes folder for routing, a controllers folder (with all the logic) and main file server.js with following:
require('./models/notifications');
require('./models/articles');
const
notificationRouter = require('./routes/notifications'),
articleRouter = require('./routes/articles');
app.use('/notifications', notificationRouter);
app.use('/articles', articleRouter);
File routes/notifications.js
const
router = require('express').Router(),
controller = require('../controllers/notifications');
router.route('/')
.get(controller.getAll)
.post(controller.create);
router.route('/:id')
.put(controller.seen);
module.exports = router;
File routes/articles.js
const
router = require('express').Router(),
controller = require('../controllers/articles');
router.route('/:articleId/comments')
.post(controller.insertComment);
module.exports = router;
I also have a middleware function that ensures access only for people logged in. My question is, where should I put the middleware to make it as clean as possible? My concerns are:
- The middleware is needed in different places
- Notification routes are all for just logged in users, so it could be in server.js in app.use() function
- But article routes have more variety, e.g. everybody can see article, but just logged in users can comment it. So I have to have the middleware inside routing file.
- Is this good place to use global function (for the middleware)?
- Do I really need same require function (of just one middleware) in many routing files?
Thanks for all and any advices or criticism of my clean solution.