I'm searching for assist with a design pattern for developing a database connection during my node.js application.

It appears apparent to complete:

module1:

var db;
exports.get_db = function(callback) {

  if (db == null) {
    dblibrary.create(connection_params, function(error, conn) {
      if (error == null) {
        db = conn;
        callback(null, db);
      }
    });
  } else {
    callback(null, db);
  }
};

module2:

exports.do_something = function () {
  module1.get_db(function (err, conn) {
    if (err == null) {
      // continue using query
    }
  });
};

It appears painful to need to penalize each and every person who would like to obtain the db reference to the advantages of utilizing a callback.

I possibly could do that:

module1:

var db;

dblibrary.create_connection(connection_params, function (err, conn) {

  if (err != null) {
     console.log("can't create connection");
     console.log(err);
     process.exit();
  } else {
     db = conn;
  }
});

exports.get_db = function() {
  return db;
};

This causes it to be to ensure that obtaining the db connection is quick and easy, but means we must "wait" at node startup time for that link with be established.

The better design? It is possible to better method of doing things?

mydb.js module:

var db
exports.db = function() {
    if (db === null) {
        db = dblibrary.createClient()
    }
    return db
}

Other modules:

var db = require('mydb').db()
...
db.query(...)

This produces the DB client instance once at startup. I love this solution since the creation code is exemplified inside a separate module and also the other modules can obtain access to the customer with one require() statement.

Best solution I have seen with this is:

in start.js:

    function init_done() {

      app.listen(8080);

    }


init_databases(init_done);

in databases.js:

init_databases(init_done_cb) {

  db.create_async(/* connect data */ , function (err, res) {

    if (err == null) init_done_cb();

  });
}

By doing this that you can do the async startup from the database server without that awkward / harmful waiting period.