peterremec peterremec - 3 months ago 29
Node.js Question

Node js database connection in a separate module

I made node.js app that includes some REST services. Those services connect to a database (for example Oracle or DB2) to execute some query.

Since I'm a beginner in node.js programming, I have a question about my case:
What's the right way to access to a database? Is it better to have one connection reference while the app is running and use the same connection instance when REST services are called?

I found some examples that includes database connection in a separate module and use that module in app, something like that:

db2.js:

var db2 = require('ibm_db');

var db2ConnSettings = "DRIVER={DB2};DATABASE=mydb;HOSTNAME=localhost;UID=db2test;PWD=db2test;PORT=50000;PROTOCOL=TCPIP";

var db2Conn = db2.open(db2ConnSettings, function(err, conn) {
if (err)
return console.log(err);
});

module.exports = db2Conn;


server.js:

var express = require('express');
var app = express();
var db2Connection = require('./db2.js');

app.get('/data', function(req, res) {
console.log(db2Connection );
// make some query
});


When this service is called,
db2connection
is
undefined
. How come? How should I retrieve a db2 connection from
db2.js
file?

Answer

As said by @Sirko:

db2.js

var db2 = require('ibm_db');
var db2ConnSettings = "DRIVER={DB2};DATABASE=mydb;HOSTNAME=localhost;UID=db2test;PWD=db2test;PORT=50000;PROTOCOL=TCPIP";

var err, conn;
var callbacks = [];

module.exports = function(callback) {
  // db2 module is called

  if (err || conn) {
    // connection has already been established
    //   (results of db2.open have been stored)
    // callback immediately
    callback(err, conn);
  }
  else {
    // connection has not been established
    // store the callback for when db connects
    callbacks.push(callback);
  }
};

db2.open(db2ConnSettings, function(_err, _conn){
  // db has connected

  err = _err; conn = _conn; // store results
  var next_callback;

  // array.pop() removed the last item from the array
  // and returns it. if no items are left, returns null.
  // so this loops through all stored callbacks.
  while(next_callback = callbacks.pop()) {
    // the removed item is stored in next_callback
    next_callback(err, conn); // send connection results to callback
  }

  // no more items in callbacks to trigger
});

server.js

var express = require('express');
var app = express();
var db2Connection = require('./db2.js')(function(err, conn) {
  // triggered if the connection has already been established
  // or as soon as it HAS been established
  app.get('/data', function(req, res) {
      console.log(conn);
      // ...
  });
});