Manuel
Manuel

Reputation: 9522

nodejs singelton for database connection with sequalize

I'm just being curious. What is the proper way to open a database connection in nodejs with requires and dependency injection?

In php I would have created a connection once as a singleton in an global variable. However this seems not to be best practice in node. Thus I had the following questions:

  1. Where would you open a db connection in node?
  2. Would you open the db connection once or multiple times?
  3. How can I open the db connection only once while keeping es6 module imports?
  4. How can I open multiple db connections through es6 module loading?
  5. If I import the same database multiple times, does it result in multiple connections?
  6. I rather know and like to control how many connections are opend by my server. E.g. if I write a backend worker with low db access I rather only open one db connection there as running an express server I'd like to open a connection per request. How can I achieve this?

I do know there are similar questions however the not fully seem to answer my question:

So my basic idea is:

/* DbService.js */
var Sequelize = require('sequelize');
module.export = new Sequelize('database', 'username')

same with models / instances

/* Foo.js */
var db = require("DbService.js");
export var Foo = db.define('foo', {...});

And in the code I than load the db / model by

/* server.js */

import Foo from './Foo';
Foo.findById('123').then(function(foo) {
    ...
};

var db = require("DbService.js");    
db.query("SELECT * FROM `test`");

However in my mind this allways opens a seperate db connection and this feels wrong. So how would you do this probably?

Upvotes: 3

Views: 1795

Answers (1)

code-jaff
code-jaff

Reputation: 9330

  1. Usually when the app gets loaded, but not necessarily - for eg. you might need to check for authentication against the stored credentials on DB.
  2. Since you tagged sequelizejs, you're not creating individual connection when creating new Sequelize instance, rather you create connection pool. If you don't specify configs for pooling sequelize will create with max 1 connection by default.
  3. By creating an instance of sequelize (new Sequelize()) you're just initializing the connection pool. The actual connection will be created and kept in pool when an actual needs comes up like performing a query.
  4. You can create a connection pool which can handle multiple connections by passing appropriate pool config option.
  5. Assuming by database you mean Sequelize instance, because of the nature of nodejs's module caching you'll always end up in same instance therefore same connection pool.
  6. Connection per request is a bad idea in general, since making a connection is relatively a resource consuming operation. Instead make use of connection pool. Since you use Sequelize, it saves your time already.

NOTE - ES6 Modules not implemented yet in nodejs.

Upvotes: 1

Related Questions