node.js design pattern for creating db connection once
mydb.js
module:
var dbexports.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.
Best answer I've seen for 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(); });}
This way you can do the async startup of the database server without that awkward / dangerous waiting period.
I wrote connect-once just for solving this kind of problems. There are two main goals, that are achived by this module:
- Connection should be initialized before request arrives
- Connection should be initialized once, even there are multiple requests coming in at the same time
You can look at express-mongo-db and express-mongoose-db as examples of usage.