Skip to content

Commit 57e93b5

Browse files
authored
Return the client instance in the connect() method (#3564)
* Return the client instance in the `connect()` method * Added one basic test * Renamed * Testing the result * Added equality check * Simplified docs for connecting * Added it to the native client as well * Added this to the callback
1 parent 5b68a11 commit 57e93b5

File tree

4 files changed

+12
-7
lines changed

4 files changed

+12
-7
lines changed

docs/pages/index.mdx

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,7 @@ The simplest possible way to connect, query, and disconnect is with async/await:
4444

4545
```js
4646
import { Client } from 'pg'
47-
const client = new Client()
48-
await client.connect()
47+
const client = await new Client().connect();
4948

5049
const res = await client.query('SELECT $1::text as message', ['Hello world!'])
5150
console.log(res.rows[0].message) // Hello world!
@@ -83,5 +82,3 @@ console.log(res.rows[0].message) // Hello world!
8382
```
8483

8584
Our real-world apps are almost always more complicated than that, and I urge you to read on!
86-
87-

packages/pg/lib/client.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ class Client extends EventEmitter {
213213
if (error) {
214214
reject(error)
215215
} else {
216-
resolve()
216+
resolve(this)
217217
}
218218
})
219219
})

packages/pg/lib/native/client.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ Client.prototype._connect = function (cb) {
119119
self.emit('connect')
120120
self._pulseQueryQueue(true)
121121

122-
cb()
122+
cb(null, this)
123123
})
124124
})
125125
}
@@ -135,7 +135,7 @@ Client.prototype.connect = function (callback) {
135135
if (error) {
136136
reject(error)
137137
} else {
138-
resolve()
138+
resolve(this)
139139
}
140140
})
141141
})

packages/pg/test/integration/client/promise-api-tests.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,14 @@ suite.test('valid connection completes promise', () => {
2020
})
2121
})
2222

23+
suite.test('valid connection returns the client in a promise', () => {
24+
const client = new pg.Client()
25+
return client.connect().then((clientInside) => {
26+
assert.equal(client, clientInside)
27+
return client.end().then(() => {})
28+
})
29+
})
30+
2331
suite.test('invalid connection rejects promise', (done) => {
2432
const client = new pg.Client({ host: 'alksdjflaskdfj', port: 1234 })
2533
return client.connect().catch((e) => {

0 commit comments

Comments
 (0)