user3033490
user3033490

Reputation:

Design pattern for shared database handle in Node.JS

How do I share a database connection across various NodeJS modules? The example I have found all had a monolithic structure where the entire code was in one single app.js file.

/* main.js */
var foo = require("./foo"); 
/* express stuff ...*/
mysql = /* establish mysql connection */ 
app.get("/foo", foo.hello ); 


/* foo.js */
exports.hello = function(req, res) {
   res.send("Hello from the foo module!"); 
}

How would I access "mysql" from my module "foo"? What is the recommended design pattern for this?

Upvotes: 2

Views: 1966

Answers (2)

Chris
Chris

Reputation: 1611

You can use the module pattern to easily pass your db object (and anything else) to modules that need it.

// users.js
module.exports = function( options ) {
    var db = options.db;
    var pants = options.pants;  // or whatever

    return {
        GetUser: function( userID, callback ) {
            db.query("....", function (err, results) {
                callback(results)
            });
        },
        AnotherFunc: function (...) {},
        AndAnotherFunc: function (...) {}
    };
};

You use this module like:

// make your db connection here

var users = require('./users.js')({
    db: db,
    pants: 'blue'
});

users.GetUser( 32, function( user ) {
    console.log("I got the user!");
    console.log( user );
});

I find this to be a great way to write modules, as it's a lot like making an actual Class object, like in C++. You can even simulate 'private' methods/parameters.

Upvotes: 3

Daiwei
Daiwei

Reputation: 43526

I usually put mysql handle in a different file (module) and require the module in different routes.

I believe you also have to connect to mysql asynchronously, you can refer to this question, which uses a callback function to solve the problem.

Upvotes: 0

Related Questions