Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 862
Martin Schnurer Avatar asked Mar 11 '23 12:03

Martin Schnurer


1 Answers

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();
like image 91
s-hunter Avatar answered Apr 27 '23 16:04

s-hunter