Search code examples
node.jspostgresqlconnection-poolingnode-modulespg

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


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.


Solution

  • 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();