Node-postgres: `new Pool() instanceof Pool` is false

Created on 6 Apr 2018  ·  9Comments  ·  Source: brianc/node-postgres

Code

const assert = require('assert');
const {Pool} = require('pg');
const pg = new Pool();

assert(pg instanceof Pool);

Expected

Should run fine.

Actual

AssertionError [ERR_ASSERTION]: false == true

Versions

$ node -v
v8.11.1

$ npm -v
5.8.0

$ npm ls pg-pool
<project>
└─┬ [email protected]
  └── [email protected] 

I am building a wrapper that accepts either Pool or Connection and want to have listeners for pool's events, but not client's. To work around this issue I am using instanceof with right-hand side of Pool.super_. Not sure if this property is intended to be used that way, or won't change later since docs don't mention its existence.

assert(new Pool() instanceof pg.Pool); // throws
assert(new Pool() instanceof pg.Pool.super_); // passes

I'd propose to fix this by adding and exporting a static method that's something like Pool.new(options) instead of exporting a wrapper function. We can keep super_ on it as a property as well, so change won't be semver-breaking. If this is not feasible given dependency on pg-pool module, we can inherit from there with only difference being Pool.Client.

Most helpful comment

This will be fixed by #1541 in a new major version.

All 9 comments

Took a look at index.js, and super_ seems to be there only because util.inherits is used. That must be the reason why instanceof gets confused with pg.Pool, but not EventEmitter:

new Pool() instanceof EventEmitter;  // true
new Pool() instanceof Pool;          // false

Woult it be possible to use class BoundPool extends Pool there and add Client to options inside a constructor?

Another work-around might be to check against require('pg-pool') directly, though a bit cleaner for my taste, this has the problem of being undocumented, same as checking against pg.Pool.super_:

const {Pool: createPool} = require('pg');
const Pool = require('pg-pool');

createPool() instanceof Pool; // true

This will be fixed by #1541 in a new major version.

Still occurring in v7.17.1:

> const pg = require('pg'); pool = new pg.Pool(); pool instanceof pg.Pool
false

Also please note that pool._super no longer exists:

> const pg = require('pg'); pool = new pg.Pool(); pool._super
undefined

@alxndrsn “in a new major version”, so 8.0.0.

Aha of course, sorry for not getting that :slightly_smiling_face:

(fixed in pg 8.0.0)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gregallenvt picture gregallenvt  ·  3Comments

Cosrnos picture Cosrnos  ·  3Comments

gpanainte picture gpanainte  ·  3Comments

spollack picture spollack  ·  4Comments

dindurthy picture dindurthy  ·  4Comments