Reputation: 1502
I'm having trouble deciding/determining what the standard/best approach for passing dependencies over to my Express routes would be. The problem I'm encountering is that some of my libraries have bindings associated with them ie. my session manager is hooked up to my redis queue client. My logs have configuration settings mapping them accordingly etc.
So here are my routes:
// Include routes and endpoints
app.use(require('./routes/account')(queue, models, log));
app.use(require('./routes/message')(queue, models, log));
app.use(require('./routes/admin') (queue, models, log));
As you can see I'm passing in my dependencies as parameters. I haven't started writing my unit tests yet, but I suspect this will bring more painful when I get there.
The other thing I've thought of doing is attaching the libraries to my request object as such:
req.log = log;
req.nconf = nconf;
req.sessions = sessions;
What I'm unsure of is: a) what the best/standard practice is, b) do any of these methods impact performance/memory usage, c) how will this impact my future unit testing.
Any insights on this would be great!
Thanks.
Upvotes: 2
Views: 43
Reputation: 1785
You might also consider requiring the libraries at the top of the file as needed.
So in the example with the log it would be something like:
var log = require('myLogger');
// or require('../path/to/logger') if it's your own module
Then you can go on to use the log in that file.
In the case of models, it makes it more clear by just including the one you need. Ex:
// messageHandler.js
var Message = require('../models/message');
function sendMessage(params){
// do some logic on params
Message.send(params);
}
This works well for unit testing, because you can require things as needed, and also stub things by just changing which file you're requiring.
I hope this helps!
Upvotes: 1
Reputation: 1598
I would set them at the app level:
app.set('queue', queue)
Then pass your app to your routing functions:
app.use(require ('./routes/admin')(app))
Then retrieve:
queue = app.get('queue')
Upvotes: 1