I was doing something like that last night (well, 2am on an airplane
over the Atlantic).
To simplify my example, let's say I have customers and orders. I have
routes that modify a customer and ones that modify an order.
I initialize my db in app.js, and then pass it into the require of a
customer and an order object:
var db, customer, order, server;
db = dbsetupfn();
customer = require('./models/customer')(db);
order = require('./models/order')(db);
server.get("/customer/:id",customer.get,customer.send);
server.get("/order/:id",order.get,order.send);
The actual customer or order lib uses a closure to store the db
object, e.g.
// this is customer.js
module.exports = function(db) {
return {
get: function(req,res,next) {
// get from the db and do other routing stuff
},
set: function(req,res,next) {
// set to the db and do other routing stuff
}
}
}
An alternative approach is to have a global route that stores the db
on the req object:
var db, server;
db = dbsetupfn();
server.use(function(req,res,next) {
req.dbobj = db;
});
server.use(server.router);
// now configure your routes
I like separating out customer, order, etc. as outside objects, as it
makes app.js extremely clean, keeps it model-like in one file, and
allows modifying one file without modifying the others, thus reducing
risk. In truth, you can use both, and it is just a question of if the
db is passed in initialization and thus available due to closure, or
is in the req object.
Avi