Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing pg-pool via module exports

Tags:

After reading the docs: https://github.com/brianc/node-pg-pool, I am slightly concerned about reusing the new Pool() method.

The docs suggests that I need to place the new Pool() before exports and return it like so

// db.js
const pool = new Pool();
module.exports = () => { return pool; }

This way I can reuse Pool until the idleTimeoutMillis or client.release(), by using require() from other files Eg:

const connect = require('./db')
connect().query(' .... ');  

If this is correct, how does it work? Does node.js caches the new Pool(), as it not inside module.exports?

like image 661
Antartica Avatar asked Aug 21 '16 00:08

Antartica


1 Answers

Yes, it is effectively cached since you create it exactly once (and node caches modules) and you always refer to that same instance in your exported method.

like image 110
mscdex Avatar answered Sep 23 '22 16:09

mscdex