I'm figuring out different ways of doing things in node at the moment, and was wondering what would be the best way of passing required context to my Models and Controllers since I keep them as separate files.
For example, this is my folder structure:
Models
- Index.js
- User.js
- Post.js
...
Controllers
- Index.js
- Home.js
- Profile.js
- Login.js
...
Routes
- common.js
- auth.js
- api.js
Views
- (Not important)
I than have index.js
in my root folder where I'd like to load all libraries (express, mongo, ...
) and use them in all my controllers and models. Usually I connect models and controllers in my routes files for example in common.js
.
Here is outline of my project files for better understanding:
index.js
// Libraries
var exp = require('express'),
hbs = require('express-handlebars');
...
// Routes
require('./rut/common.js')(app, mon);
require('./rut/api.js')(app, mon);
...
routes/common.js
// Load Models
var mod = require('../mod')(mon);
// Load Controllers
var ctr = require('../ctr');
module.exports = function (app, mon) {
// Home Page
app.get('/', ctr.Home);
// Routes and stuff...
};
controllers/Home.js
// Home Controller
module.exports = function (req, res) {
res.render('home');
console.log(mod.Task);
};
So, my main concern here is that I would have to wrap every single controllers/x.js
file in some function to pass important objects like mongo
, app
and express
to its scope and also call it with all those required arguments like require('./Home.js')(app, express, mongo, ...)
.
I can write some loader in controllers/index.js
file which requires all files from current dir and passes them required scope automatically but I was wondering if there was some more elegant/native solution to that problem other than lots of repetitive code that wraps each controller or model.