Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(listen): makes sure unlisten returns a reference to conn result #160

Merged
merged 2 commits into from
Mar 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -341,15 +341,19 @@ function Postgres(a, b) {

if (channel in listeners) {
listeners[channel].push(fn)
return Promise.resolve(Object.assign({}, listener.result, { unlisten }))
return Promise.resolve(Object.create(listener.result, {
unlisten: { value: unlisten }
}))
}

listeners[channel] = [fn]

return query({ raw: true }, listener.conn, 'listen ' + escape(channel))
.then((result) => {
listener.result = result
return Object.assign({}, listener.result, { unlisten })
Object.assign(listener.result, result)
return Object.create(listener.result, {
unlisten: { value: unlisten }
})
})

function unlisten() {
Expand Down Expand Up @@ -382,8 +386,8 @@ function Postgres(a, b) {
},
options
))
listener = { conn, result: null }
all.push(conn)
listener = { conn, result: {} };
all.push(conn);
return listener
}

Expand Down
14 changes: 14 additions & 0 deletions tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,20 @@ t('listen reconnects', async() => {
return ['ab', xs.join('')]
})

t('listen result reports correct connection state after reconnection', async() => {
const listener = postgres(options)
, xs = []

const result = await listener.listen('test', x => xs.push(x))
const initialPid = result.state.pid
await sql.notify('test', 'a')
await sql`select pg_terminate_backend(${ initialPid }::int)`
await delay(50)
listener.end()

return [result.state.pid !== initialPid, true]
})

t('unlisten removes subscription', async() => {
const listener = postgres(options)
, xs = []
Expand Down