Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sharing objects and avoiding globals in node.js

Sharing objects and avoiding globals in node.js

Problem

What would be the most appropriate way of sharing the database connection in the below snippet ( the db variable) with my routers/controllers without turning the db variable into a global?

var mongo = require('mongoskin'),
db = mongo.db(config.db.adress);

app.use(function(req, res, next) {
    db.open(function(err, data) {
        (err) ? res.send('Internal server error', 500) : next();
    });
});

// Setting up controllers here
app.post('/users', require('./controllers/users').create);

Coming from a PHP background, I came to think about Dependency Injection, but I have no idea if that's appropriate in node.

Problem courtesy of: Industrial

Solution

Try look at this way:

app.js:

var mongo = require('mongoskin'),
db = mongo.db(config.db.adress);

app.use(function(req, res, next) {
    db.open(function(err, data) {
        (err) ? res.send('Internal server error', 500) : next();
    });
});

require('./controllers/users')(app, db);

controllers/users.js:

module.exports = function (app, db) {

    app.post('/users', function(req, res, next) {
        // Your create function
        // Link to db exists here
    });

};
Solution courtesy of: Vadim Baryshev

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Sharing objects and avoiding globals in node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×