Skip to content

Commit 001771f

Browse files
committed
Connect hook working
1 parent d9a83be commit 001771f

2 files changed

Lines changed: 68 additions & 1 deletion

File tree

packages/pg-pool/index.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,19 @@ class Pool extends EventEmitter {
278278
this.log('new client connected')
279279

280280
if (this.options.hooks && this.options.hooks.connect) {
281-
const hookResult = this.options.hooks.connect(client)
281+
let hookResult
282+
try {
283+
hookResult = this.options.hooks.connect(client)
284+
} catch (hookErr) {
285+
this._clients = this._clients.filter((c) => c !== client)
286+
client.end(() => {
287+
this._pulseQueue()
288+
if (!pendingItem.timedOut) {
289+
pendingItem.callback(hookErr, undefined, NOOP)
290+
}
291+
})
292+
return
293+
}
282294
if (hookResult && typeof hookResult.then === 'function') {
283295
hookResult.then(
284296
() => {

packages/pg-pool/test/lifecycle-hooks.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,59 @@ describe('lifecycle hooks', () => {
2222
client.release()
2323
await pool.end()
2424
})
25+
26+
it('are called on connect with an async hook', async () => {
27+
const pool = new Pool({
28+
hooks: {
29+
connect: async (client) => {
30+
const res = await client.query('SELECT 1 AS num')
31+
client.HOOK_CONNECT_RESULT = res.rows[0].num
32+
},
33+
},
34+
})
35+
const client = await pool.connect()
36+
expect(client.HOOK_CONNECT_RESULT).to.equal(1)
37+
const res = await client.query('SELECT 1 AS num')
38+
expect(res.rows[0].num).to.equal(1)
39+
client.release()
40+
const client2 = await pool.connect()
41+
expect(client).to.equal(client2)
42+
expect(client2.HOOK_CONNECT_RESULT).to.equal(1)
43+
client.release()
44+
await pool.end()
45+
})
46+
47+
it('errors out the connect call if the async connect hook rejects', async () => {
48+
const pool = new Pool({
49+
hooks: {
50+
connect: async (client) => {
51+
await client.query('SELECT INVALID HERE')
52+
},
53+
},
54+
})
55+
try {
56+
await pool.connect()
57+
throw new Error('Expected connect to throw')
58+
} catch (err) {
59+
expect(err.message).to.contain('invalid')
60+
}
61+
await pool.end()
62+
})
63+
64+
it('errors out the connect call if the connect hook throws', async () => {
65+
const pool = new Pool({
66+
hooks: {
67+
connect: () => {
68+
throw new Error('connect hook error')
69+
},
70+
},
71+
})
72+
try {
73+
await pool.connect()
74+
throw new Error('Expected connect to throw')
75+
} catch (err) {
76+
expect(err.message).to.equal('connect hook error')
77+
}
78+
await pool.end()
79+
})
2580
})

0 commit comments

Comments
 (0)