Skip to content

Commit

Permalink
Make native non-enumerable (#2065)
Browse files Browse the repository at this point in the history
* Make `native` non-enumerable

Making it non-enumerable means less spurious "Cannot find module"
errors in your logs when iterating over `pg` objects.

`Object.defineProperty` has been available since Node 0.12.

See #1894 (comment)

* Add test for `native` enumeration

Co-authored-by: Gabe Gorelick <gabegorelick@gmail.com>
  • Loading branch information
brianc and gabegorelick committed Jan 15, 2020
1 parent 5b01eb0 commit 8494cb4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 13 deletions.
34 changes: 21 additions & 13 deletions packages/pg/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,28 @@ if (typeof process.env.NODE_PG_FORCE_NATIVE !== 'undefined') {
module.exports = new PG(Client)

// lazy require native module...the native module may not have installed
module.exports.__defineGetter__('native', function () {
delete module.exports.native
var native = null
try {
native = new PG(require('./native'))
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') {
throw err
Object.defineProperty(module.exports, 'native', {
configurable: true,
enumerable: false,
get() {
var native = null
try {
native = new PG(require('./native'))
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') {
throw err
}
/* eslint-disable no-console */
console.error(err.message)
/* eslint-enable no-console */
}
/* eslint-disable no-console */
console.error(err.message)
/* eslint-enable no-console */

// overwrite module.exports.native so that getter is never called again
Object.defineProperty(module.exports, 'native', {
value: native
})

return native
}
module.exports.native = native
return native
})
}
11 changes: 11 additions & 0 deletions packages/pg/test/integration/gh-issues/1992-tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

"use strict"
const helper = require('./../test-helper')
const assert = require('assert')

const suite = new helper.Suite()

suite.test('Native should not be enumerable', () => {
const keys = Object.keys(helper.pg)
assert.strictEqual(keys.indexOf('native'), -1)
})

0 comments on commit 8494cb4

Please sign in to comment.