node-express-sequelize-es2015
node-express-sequelize-es2015 copied to clipboard
How to access app?
Could someone please guide me how this structure recommends to access the app-object when the project is running? For example, in the libs-folder, what if a separate help-file is included that must access some model of Sequelize, how would that be done?
Is it only by adding more files to consign in index or are there any other preferred methods? Do you really prefer consign over other alternativs to access singleton data?
Thanks!
Hi!
I see 3 different ways to organize an express app.
1 Require the things you need, where you need it
2 Injecting the components you will often use in the app object.
You can either use consign or doing it yourself like this:
// index.js
...
const db = require('./db')(app);
...
// db.js
module.exports = app => {
const db = {};
// do what you have to do to configure the db variable.
app.db = db;
return db;
}
At first I was thinking consign is cool, but now I think that it obfuscates more the code than it adds value. I would not use it. The code above seems easier to understand, in my opinion. Using this approach, I would just add in the app object the things that are core elements, like db and models. And then I would require the things I need where I need it, or user dependency injection.
To answer your question, you have to pass the app object from index.js to all way down you need it in your code.
3 Dependency injection
When I say 'dependency injection', I mean having an architecture where you pass the things you need from top to bottom, like this:
// index.js
const db = require('./db');
const auth = require(‘./auth’);
const models = require('./models')(db, auth);
Note that the first solution is a kind of dependency injection too. For me, the main advantage of doing this is testability. You can very easily unit tests each component of your app without having to do things like stubbing or other kinds of injections.
More about dependency injection: https://www.youtube.com/watch?v=0ZNIQOO2sfA
Conclusion
I don’t think any of these solutions are bad as long as you separate well each concerns: models, routes, middlewares, db initialization, etc.
What I often do today is a mix of the first and second approach, and I don't use concern anymore.
I wish I answer your question. Also, it is an open subject.