Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js design pattern for creating db connection once

I am looking for help with a design pattern for creating a database connection in my node.js application.

It seems obvious to do:

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 seems painful to have to penalize every single person who wants to get the db connection with the requirement of using a callback.

I could do this:

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 makes it so that getting the db connection is simple and fast, but means we have to "wait" at node startup time for the connection to be established.

Which is the better design? Is there a better way of doing things?

like image 463
MarcWan Avatar asked Jun 08 '11 07:06

MarcWan


People also ask

Which design pattern is best for Node JS?

Because of this behaviour of require , singletons are probably the most common Node. js design patterns among the modules in NPM. npm is used by open source developers from all around the world to share and borrow code, as well as many businesses.

How do you implement factory design pattern in node JS?

Implement simple Factory Pattern in Nodejsclass Car { constructor(name) { this.name = name + '-' + Math. random(). toString(36). substring(2, 15); } showInfo() { console.

What is Node JS design patterns?

Design patterns, simply put, are a way for you to structure your solution's code in a way that allows you to gain some kind of benefit. Such as faster development speed, code reusability, and so on. All patterns lend themselves quite easily to the OOP paradigm.


1 Answers

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 creates the DB client instance once at startup. I like this solution because the creation code is encapsulated in a separate module and the other modules can get access to the client with one require() statement.

like image 176
alienhard Avatar answered Oct 16 '22 00:10

alienhard