How to share connection pool between modules in node.js?
Asked Answered
R

2

6

I have a little or no knowledge at how to properly implement postgres connection pool in node.js modules.

My question is : Is it problem when I am creating new Pool in every module where I need a connection to pg ?

Is there a way to create pool globally for a whole app ?

Thanks.

Ramires answered 3/8, 2016 at 15:29 Comment(0)
S
9

Define the pool in a file say pgpool.js

var pg = require('pg');
var pool;
var config = {
  user: 'foo',
  database: 'my_db',
  password: 'secret',
  port: 5432, 
  max: 10,
  idleTimeoutMillis: 30000,
};

module.exports = {
    getPool: function () {
      if (pool) return pool; // if it is already there, grab it here
      pool = new pg.Pool(config);
      return pool;
};

Use it like this:

var db = require('./a/path/to/pgpool.js');
var pool = db.getPool();
Schaefer answered 3/8, 2016 at 15:50 Comment(2)
Alternatively, you can use module.exports = new pg.Pool(config). Because of module caching, this will always return the same instance of the pool to each file that require's it.Enchondroma
I can confirm this works for the mysql npm package also. ThanksGiess
V
1

I would suggest to not export the pool, but a function that provides a connection to it. Using promise-mysql

var mysql = require('promise-mysql');

var connectionPool = mysql.createPool({
  host     : "127.0.0.1",
  user     : '******',
  password : '******',
  database : '******',
  port     : '3306'
});

module.exports={

  getConnection: function(){
    return new Promise(function(resolve,reject){
      connectionPool.getConnection().then(function(connection){
        resolve(connection);
      }).catch(function(error){
        reject(error);
      });
    });
  }
} 

I have made a simple blog post about MySQL pool sharing, where you can read more

Volitant answered 25/4, 2017 at 16:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.