Skip to content

Commit 03188a5

Browse files
committed
Periodically check if client connection is closed because node pg will not fulfill promise after that.
1 parent 1a090e3 commit 03188a5

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "tinypg",
3-
"version": "2.0.0-alpha.13",
3+
"version": "2.0.0-alpha.14",
44
"description": "Easy way to call sql files using postgres.",
55
"main": "dist/index.js",
66
"typings": "dist/index.d.ts",

src/tiny.ts

+21-1
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,27 @@ export class TinyPg {
189189

190190
this.events.emit('query', query_context)
191191

192+
let call_completed = false
193+
194+
// Work around node-postgres swallowing queries after a connection error
195+
// https://github.com/brianc/node-postgres/issues/718
196+
const connection_failed_promise = new Promise<T.Result<T>>((resolve, reject) => {
197+
const checkForConnection = () => {
198+
if (call_completed) {
199+
resolve()
200+
} else if (client['connection'].stream.destroyed) {
201+
reject(new Error('Connection terminated'))
202+
} else {
203+
setTimeout(checkForConnection, 500)
204+
}
205+
}
206+
207+
setTimeout(checkForConnection, 500)
208+
})
209+
192210
const callComplete = _.once((error: Error, data: T.Result<T>) => {
211+
call_completed = true
212+
193213
if (error && (!error['code'] || _.startsWith(error['code'], '57P'))) {
194214
(<any>client).release(error)
195215
} else {
@@ -235,7 +255,7 @@ export class TinyPg {
235255
})
236256
})
237257

238-
return query_promise
258+
return Promise.race([ connection_failed_promise, query_promise ])
239259
.then(result => {
240260
callComplete(null, result)
241261
return result

0 commit comments

Comments
 (0)