Skip to content

Commit 20d2c08

Browse files
Make async/await the primary examples in the docs (#2932)
* Correctly capitalize GitHub * Add note on callbacks to index * Add note on error handling * Update client examples to use promises * Update pooling examples * Fix readme link * Update cursor docs * Update connecting examples * Update Queries * Update examples in pooling * Update trx examples * Update SSL example * Update example * Use ESM instead of CJS * Update docs/pages/apis/cursor.mdx Co-authored-by: Charmander <[email protected]> * Update docs/pages/apis/cursor.mdx Co-authored-by: Charmander <[email protected]> * Update docs/pages/apis/pool.mdx Co-authored-by: Charmander <[email protected]> * Update docs/pages/apis/pool.mdx Co-authored-by: Charmander <[email protected]> * Update docs/pages/apis/pool.mdx Co-authored-by: Charmander <[email protected]> * Update docs/pages/features/connecting.mdx Co-authored-by: Charmander <[email protected]> * Update docs/pages/features/connecting.mdx Co-authored-by: Charmander <[email protected]> * Update docs/pages/features/ssl.mdx Co-authored-by: Charmander <[email protected]> --------- Co-authored-by: Charmander <[email protected]>
1 parent dee3ae5 commit 20d2c08

15 files changed

+214
-616
lines changed

docs/pages/announcements.mdx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ _If you find `pg` valuable to you or your business please consider [supporting](
7979

8080
After a _very_ long time on my todo list I've ported the docs from my old hand-rolled webapp running on route53 + elb + ec2 + dokku (I know, I went overboard!) to [gatsby](https://www.gatsbyjs.org/) hosted on [netlify](https://www.netlify.com/) which is _so_ much easier to manage. I've released the code at [https://github.com/brianc/node-postgres-docs](https://github.com/brianc/node-postgres-docs) and invite your contributions! Let's make this documentation better together. Any time changes are merged to master on the documentation repo it will automatically deploy.
8181

82-
If you see an error in the docs, big or small, use the "edit on github" button to edit the page & submit a pull request right there. I'll get a new version out ASAP with your changes! If you want to add new pages of documentation open an issue if you need guidance, and I'll help you get started.
82+
If you see an error in the docs, big or small, use the "edit on GitHub" button to edit the page & submit a pull request right there. I'll get a new version out ASAP with your changes! If you want to add new pages of documentation open an issue if you need guidance, and I'll help you get started.
8383

8484
I want to extend a special **thank you** to all the [supporters](https://github.com/brianc/node-postgres/blob/master/SPONSORS.md) and [contributors](https://github.com/brianc/node-postgres/graphs/contributors) to the project that have helped keep me going through times of burnout or life "getting in the way." ❤️
8585

@@ -116,7 +116,7 @@ [email protected]
116116
To demonstrate the issue & see if you are vunerable execute the following in node:
117117

118118
```js
119-
const { Client } = require('pg')
119+
import { Client } from 'pg'
120120
const client = new Client()
121121
client.connect()
122122

docs/pages/apis/client.mdx

Lines changed: 28 additions & 119 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ type Config = {
2929
example to create a client with specific connection information:
3030
3131
```js
32-
const { Client } = require('pg')
32+
import { Client } from 'pg'
3333

3434
const client = new Client({
3535
host: 'my.database-server.com',
@@ -42,33 +42,13 @@ const client = new Client({
4242

4343
## client.connect
4444

45-
Calling `client.connect` with a callback:
46-
4745
```js
48-
const { Client } = require('pg')
46+
import { Client } from 'pg'
4947
const client = new Client()
50-
client.connect((err) => {
51-
if (err) {
52-
console.error('connection error', err.stack)
53-
} else {
54-
console.log('connected')
55-
}
56-
})
57-
```
5848

59-
Calling `client.connect` without a callback yields a promise:
60-
61-
```js
62-
const { Client } = require('pg')
63-
const client = new Client()
64-
client
65-
.connect()
66-
.then(() => console.log('connected'))
67-
.catch((err) => console.error('connection error', err.stack))
49+
await client.connect()
6850
```
6951

70-
_note: connect returning a promise only available in [email protected] or above_
71-
7252
## client.query
7353

7454
### QueryConfig
@@ -95,77 +75,43 @@ type QueryConfig {
9575
}
9676
```
9777

98-
### callback API
99-
10078
```ts
101-
client.query(text: string, values?: any[], callback?: (err: Error, result: QueryResult) => void) => void
102-
```
103-
104-
**Plain text query with a callback:**
105-
106-
```js
107-
const { Client } = require('pg')
108-
const client = new Client()
109-
client.connect()
110-
client.query('SELECT NOW()', (err, res) => {
111-
if (err) throw err
112-
console.log(res)
113-
client.end()
114-
})
79+
client.query(text: string, values?: any[]) => Promise<Result>
11580
```
11681

117-
**Parameterized query with a callback:**
82+
**Plain text query**
11883

11984
```js
120-
const { Client } = require('pg')
85+
import { Client } from 'pg'
12186
const client = new Client()
122-
client.connect()
123-
client.query('SELECT $1::text as name', ['brianc'], (err, res) => {
124-
if (err) throw err
125-
console.log(res)
126-
client.end()
127-
})
128-
```
12987

130-
### Promise API
88+
await client.connect()
13189

132-
If you call `client.query` with query text and optional parameters but **don't** pass a callback, then you will receive a `Promise` for a query result.
90+
const result = await client.query('SELECT NOW()')
91+
console.log(result)
13392

134-
```ts
135-
client.query(text: string, values?: any[]) => Promise<Result>
93+
await client.end()
13694
```
13795

138-
**Plain text query with a promise**
96+
**Parameterized query**
13997

14098
```js
141-
const { Client } = require('pg')
99+
import { Client } from 'pg'
142100
const client = new Client()
143-
client.connect()
144-
client
145-
.query('SELECT NOW()')
146-
.then((result) => console.log(result))
147-
.catch((e) => console.error(e.stack))
148-
.then(() => client.end())
149-
```
150101

151-
**Parameterized query with a promise**
102+
await client.connect()
152103

153-
```js
154-
const { Client } = require('pg')
155-
const client = new Client()
156-
client.connect()
157-
client
158-
.query('SELECT $1::text as name', ['brianc'])
159-
.then((result) => console.log(result))
160-
.catch((e) => console.error(e.stack))
161-
.then(() => client.end())
104+
const result = await client.query('SELECT $1::text as name', ['brianc'])
105+
console.log(result)
106+
107+
await client.end()
162108
```
163109

164110
```ts
165111
client.query(config: QueryConfig) => Promise<Result>
166112
```
167113

168-
**client.query with a QueryConfig and a callback**
114+
**client.query with a QueryConfig**
169115

170116
If you pass a `name` parameter to the `client.query` method, the client will create a [prepared statement](/features/queries#prepared-statements).
171117

@@ -177,42 +123,18 @@ const query = {
177123
rowMode: 'array',
178124
}
179125

180-
client.query(query, (err, res) => {
181-
if (err) {
182-
console.error(err.stack)
183-
} else {
184-
console.log(res.rows) // ['brianc']
185-
}
186-
})
187-
```
188-
189-
**client.query with a QueryConfig and a Promise**
126+
const result = await client.query(query)
127+
console.log(result.rows) // ['brianc']
190128

191-
```js
192-
const query = {
193-
name: 'get-name',
194-
text: 'SELECT $1::text',
195-
values: ['brianc'],
196-
rowMode: 'array',
197-
}
198-
199-
// promise
200-
client
201-
.query(query)
202-
.then((res) => {
203-
console.log(res.rows) // ['brianc']
204-
})
205-
.catch((e) => {
206-
console.error(e.stack)
207-
})
129+
await client.end()
208130
```
209131

210132
**client.query with a `Submittable`**
211133

212134
If you pass an object to `client.query` and the object has a `.submit` function on it, the client will pass it's PostgreSQL server connection to the object and delegate query dispatching to the supplied object. This is an advanced feature mostly intended for library authors. It is incidentally also currently how the callback and promise based queries above are handled internally, but this is subject to change. It is also how [pg-cursor](https://github.com/brianc/node-pg-cursor) and [pg-query-stream](https://github.com/brianc/node-pg-query-stream) work.
213135

214136
```js
215-
const Query = require('pg').Query
137+
import { Query } from 'pg'
216138
const query = new Query('select $1::text as name', ['brianc'])
217139

218140
const result = client.query(query)
@@ -222,9 +144,11 @@ assert(query === result) // true
222144
query.on('row', (row) => {
223145
console.log('row!', row) // { name: 'brianc' }
224146
})
147+
225148
query.on('end', () => {
226149
console.log('query done')
227150
})
151+
228152
query.on('error', (err) => {
229153
console.error(err.stack)
230154
})
@@ -237,25 +161,10 @@ query.on('error', (err) => {
237161
Disconnects the client from the PostgreSQL server.
238162

239163
```js
240-
client.end((err) => {
241-
console.log('client has disconnected')
242-
if (err) {
243-
console.log('error during disconnection', err.stack)
244-
}
245-
})
164+
await client.end()
165+
console.log('client has disconnected')
246166
```
247167

248-
Calling end without a callback yields a promise:
249-
250-
```js
251-
client
252-
.end()
253-
.then(() => console.log('client has disconnected'))
254-
.catch((err) => console.error('error during disconnection', err.stack))
255-
```
256-
257-
_note: end returning a promise is only available in pg7.0 and above_
258-
259168
## events
260169

261170
### error
@@ -264,7 +173,7 @@ _note: end returning a promise is only available in pg7.0 and above_
264173
client.on('error', (err: Error) => void) => void
265174
```
266175

267-
When the client is in the process of connecting, dispatching a query, or disconnecting it will catch and foward errors from the PostgreSQL server to the respective `client.connect` `client.query` or `client.end` callback/promise; however, the client maintains a long-lived connection to the PostgreSQL back-end and due to network partitions, back-end crashes, fail-overs, etc the client can (and over a long enough time period _will_) eventually be disconnected while it is idle. To handle this you may want to attach an error listener to a client to catch errors. Here's a contrived example:
176+
When the client is in the process of connecting, dispatching a query, or disconnecting it will catch and foward errors from the PostgreSQL server to the respective `client.connect` `client.query` or `client.end` promise; however, the client maintains a long-lived connection to the PostgreSQL back-end and due to network partitions, back-end crashes, fail-overs, etc the client can (and over a long enough time period _will_) eventually be disconnected while it is idle. To handle this you may want to attach an error listener to a client to catch errors. Here's a contrived example:
268177

269178
```js
270179
const client = new pg.Client()
@@ -301,7 +210,7 @@ type Notification {
301210

302211
```js
303212
const client = new pg.Client()
304-
client.connect()
213+
await client.connect()
305214

306215
client.query('LISTEN foo')
307216

docs/pages/apis/cursor.mdx

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ $ npm install pg pg-cursor
1818
Instantiates a new Cursor. A cursor is an instance of `Submittable` and should be passed directly to the `client.query` method.
1919

2020
```js
21-
const { Pool } = require('pg')
22-
const Cursor = require('pg-cursor')
21+
import { Pool } from 'pg'
22+
import Cursor from 'pg-cursor'
2323

2424
const pool = new Pool()
2525
const client = await pool.connect()
@@ -48,7 +48,7 @@ type CursorQueryConfig {
4848

4949
## read
5050

51-
### `cursor.read(rowCount: Number, callback: (err: Error, rows: Row[], result: pg.Result) => void) => void`
51+
### `cursor.read(rowCount: Number) => Promise<pg.Result>`
5252

5353
Read `rowCount` rows from the cursor instance. The callback will be called when the rows are available, loaded into memory, parsed, and converted to JavaScript types.
5454

@@ -57,25 +57,22 @@ If the cursor has read to the end of the result sets all subsequent calls to cur
5757
Here is an example of reading to the end of a cursor:
5858

5959
```js
60-
const { Pool } = require('pg')
61-
const Cursor = require('pg-cursor')
60+
import { Pool } from 'pg'
61+
import Cursor from 'pg-cursor'
6262

6363
const pool = new Pool()
6464
const client = await pool.connect()
6565
const cursor = client.query(new Cursor('select * from generate_series(0, 5)'))
66-
cursor.read(100, (err, rows) => {
67-
if (err) {
68-
throw err
69-
}
70-
assert(rows.length == 6)
71-
cursor.read(100, (err, rows) => {
72-
assert(rows.length == 0)
73-
})
74-
})
66+
67+
let rows = await cursor.read(100)
68+
assert(rows.length == 6)
69+
70+
rows = await cursor.read(100)
71+
assert(rows.length == 0)
7572
```
7673

7774
## close
7875

79-
### `cursor.close(callback: () => void) => void`
76+
### `cursor.close() => Promise<void>`
8077

8178
Used to close the cursor early. If you want to stop reading from the cursor before you get all of the rows returned, call this.

0 commit comments

Comments
 (0)