5

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?

Vao Tsun
  • 47,234
  • 13
  • 100
  • 132
Antartica
  • 125
  • 9

2 Answers2

4

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.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Thanks, so that means I should always export the result only without dependencies, etc... ? – Antartica Aug 21 '16 at 11:16
  • I don't understand your question. – mscdex Aug 21 '16 at 16:36
  • Sorry, actually after testing this code, I get `TypeError: connect.query is not a function`. It seems like the pool isn't initialized before `require()`. Do you know what's wrong? Reference: https://github.com/brianc/node-pg-pool#a-note-on-instances – Antartica Aug 21 '16 at 19:35
  • You're exporting a *function* that returns a db connection, so you'd need to do: `connect().query()`. – mscdex Aug 21 '16 at 20:55
  • Thanks, and what should I do to have `connect().query()` written as `connect.query()` , apart from doing this -> `const connect = connect();` – Antartica Aug 21 '16 at 21:20
  • You *could* export a function that calls `pool.connect().query(...)`, passing its arguments. – mscdex Aug 21 '16 at 22:59
  • last question... I could export `Pool()` like so `module.exports = new Pool()` (as an object). So should I `return` it as a function or use it as an object? What the best practice? – Antartica Aug 22 '16 at 00:53
  • I don't think there is a best practice, it's just whatever you find more convenient. – mscdex Aug 22 '16 at 01:27
  • @Atartica for a friendlier API that doesn't require connecting, see [pg-promise](https://github.com/vitaly-t/pg-promise) ;) – vitaly-t Aug 24 '16 at 18:14
0

Absolutely, by creating the instance just once, you allow the node to cache it, and subsequently, you maintain a consistent reference to that identical instance within your exported method