Coming from a non Node background, my first instinct is to define my service as such
MyService.js
module.exports = new function(dbConnection)
{
// service uses the db
}
Now, I want one open db connection per request, so I define in middleware:
res.locals.db = openDbConnection();
And in some consuming Express api code:
api.js
var MyService = require(./services/MyService')
...
router.get('/foo/:id?', function (req, res) {
var service = new MyService(res.locals.db);
});
Now, being that Node's preferred method of dependency injection is via the require(...)
statement, it seems that I shouldn't be using the constructor of MyService
for injection of the db
.
So let's say I want to have
var db = require('db');
at the top of MyService
and then use somehow like db.current
....but how would I tie the db to the current res.locals
object now that db
is a module itself? What's a recommended way of handling this kind of thin in Node?