Reputation: 410
So I'm in the process of separating my express app into modules, and I have a question.
Currently my app.js contains:
var db = module.exports.db = require('./helpers/db')(app.set('database'))
and model files contain:
var DB = require('../app').db;
After reading This, it seems like one way to structure the modules would be to export app and require app from within the module, and then require that module directly down the road.
That would mean in my db.js I would require require('../app'), and in my models I would db = require('db').
Currently db.js returns a new instance of a mysql connection:
module.exports = function(settings) {
return new MysqlDB(settings);
}
Am I wrong to believe moving module.exports.db out of app.js, and requiring db.js directly in each model would create multiple instances of the connection?
I wrote this a little confused myself, so please let me know where I can improve the question. Any and all tips are welcome, I really want to get a better understand of it all.
thanks!
Upvotes: 3
Views: 664
Reputation: 23070
I would lean towards pushing the requirement into the module as opposed to the module having to be aware of where to grab an instance of the db object. This reduces coupling and makes it easier to inject a mock db object for testing purposes.
Upvotes: 1