Skip to content

Commit 54f33ba

Browse files
authored
Modernize examples in readme (#213)
* Modernize examples in readme * Also update examples/*
1 parent 70f3755 commit 54f33ba

File tree

7 files changed

+136
-117
lines changed

7 files changed

+136
-117
lines changed

README.md

+52-46
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,9 @@ Batching is not an advanced feature, it's DataLoader's primary feature.
5353
Create loaders by providing a batch loading function.
5454

5555
```js
56-
var DataLoader = require('dataloader')
56+
const DataLoader = require('dataloader')
5757

58-
var userLoader = new DataLoader(keys => myBatchGetUsers(keys));
58+
const userLoader = new DataLoader(keys => myBatchGetUsers(keys))
5959
```
6060

6161
A batch loading function accepts an Array of keys, and returns a Promise which
@@ -66,14 +66,14 @@ individual loads which occur within a single frame of execution (a single tick
6666
of the event loop) and then call your batch function with all requested keys.
6767

6868
```js
69-
userLoader.load(1)
70-
.then(user => userLoader.load(user.invitedByID))
71-
.then(invitedBy => console.log(`User 1 was invited by ${invitedBy}`));
69+
const user = await userLoader.load(1)
70+
const invitedBy = await userLoader.load(user.invitedByID)
71+
console.log(`User 1 was invited by ${invitedBy}`)
7272

7373
// Elsewhere in your application
74-
userLoader.load(2)
75-
.then(user => userLoader.load(user.lastInvitedID))
76-
.then(lastInvited => console.log(`User 2 last invited ${lastInvited}`));
74+
const user = await userLoader.load(2)
75+
const lastInvited = await userLoader.load(user.lastInvitedID)
76+
console.log(`User 2 last invited ${lastInvited}`)
7777
```
7878

7979
A naive application may have issued four round-trips to a backend for the
@@ -144,9 +144,9 @@ In addition to relieving pressure on your data storage, caching results per-requ
144144
also creates fewer objects which may relieve memory pressure on your application:
145145

146146
```js
147-
var userLoader = new DataLoader(...)
148-
var promise1A = userLoader.load(1)
149-
var promise1B = userLoader.load(1)
147+
const userLoader = new DataLoader(...)
148+
const promise1A = userLoader.load(1)
149+
const promise1B = userLoader.load(1)
150150
assert(promise1A === promise1B)
151151
```
152152

@@ -172,11 +172,11 @@ function createLoaders(authToken) {
172172
}
173173
}
174174

175-
var app = express()
175+
const app = express()
176176

177177
app.get('/', function(req, res) {
178-
var authToken = authenticateUser(req)
179-
var loaders = createLoaders(authToken)
178+
const authToken = authenticateUser(req)
179+
const loaders = createLoaders(authToken)
180180
res.send(renderPage(req, loaders))
181181
})
182182

@@ -195,18 +195,17 @@ Here's a simple example using SQL UPDATE to illustrate.
195195

196196
```js
197197
// Request begins...
198-
var userLoader = new DataLoader(...)
198+
const userLoader = new DataLoader(...)
199199

200200
// And a value happens to be loaded (and cached).
201-
userLoader.load(4).then(...)
201+
const user = await userLoader.load(4)
202202

203203
// A mutation occurs, invalidating what might be in cache.
204-
sqlRun('UPDATE users WHERE id=4 SET username="zuck"').then(
205-
() => userLoader.clear(4)
206-
)
204+
await sqlRun('UPDATE users WHERE id=4 SET username="zuck"')
205+
userLoader.clear(4)
207206

208207
// Later the value load is loaded again so the mutated data appears.
209-
userLoader.load(4).then(...)
208+
const user = await userLoader.load(4)
210209

211210
// Request completes.
212211
```
@@ -221,12 +220,14 @@ be cached to avoid frequently loading the same `Error`.
221220
In some circumstances you may wish to clear the cache for these individual Errors:
222221

223222
```js
224-
userLoader.load(1).catch(error => {
225-
if (/* determine if should clear error */) {
226-
userLoader.clear(1);
223+
try {
224+
const user = await userLoader.load(1)
225+
} catch (error) {
226+
if (/* determine if the error should not be cached */) {
227+
userLoader.clear(1)
227228
}
228-
throw error;
229-
});
229+
throw error
230+
}
230231
```
231232

232233
#### Disabling Cache
@@ -244,7 +245,7 @@ for each instance of the requested key.
244245
For example:
245246

246247
```js
247-
var myLoader = new DataLoader(keys => {
248+
const myLoader = new DataLoader(keys => {
248249
console.log(keys)
249250
return someBatchLoadFn(keys)
250251
}, { cache: false })
@@ -263,7 +264,7 @@ enabled, but will immediately clear its cache when the batch function is called
263264
so later requests will load new values.
264265

265266
```js
266-
var myLoader = new DataLoader(keys => {
267+
const myLoader = new DataLoader(keys => {
267268
identityLoader.clearAll()
268269
return someBatchLoadFn(keys)
269270
})
@@ -310,16 +311,16 @@ Loads a key, returning a `Promise` for the value represented by that key.
310311
Loads multiple keys, promising an array of values:
311312

312313
```js
313-
var [ a, b ] = await myLoader.loadMany([ 'a', 'b' ]);
314+
const [ a, b ] = await myLoader.loadMany([ 'a', 'b' ])
314315
```
315316

316317
This is equivalent to the more verbose:
317318

318319
```js
319-
var [ a, b ] = await Promise.all([
320+
const [ a, b ] = await Promise.all([
320321
myLoader.load('a'),
321322
myLoader.load('b')
322-
]);
323+
])
323324
```
324325

325326
- *keys*: An array of key values to load.
@@ -378,7 +379,7 @@ When using DataLoader, we could define the `User` type using the
378379
and possibly fewer if there are cache hits.
379380

380381
```js
381-
var UserType = new GraphQLObjectType({
382+
const UserType = new GraphQLObjectType({
382383
name: 'User',
383384
fields: () => ({
384385
name: { type: GraphQLString },
@@ -391,9 +392,12 @@ var UserType = new GraphQLObjectType({
391392
first: { type: GraphQLInt }
392393
},
393394
type: new GraphQLList(UserType),
394-
resolve: (user, { first }) => queryLoader.load([
395-
'SELECT toID FROM friends WHERE fromID=? LIMIT ?', user.id, first
396-
]).then(rows => rows.map(row => userLoader.load(row.toID)))
395+
resolve: async (user, { first }) => {
396+
const rows = await queryLoader.load([
397+
'SELECT toID FROM friends WHERE fromID=? LIMIT ?', user.id, first
398+
])
399+
return rows.map(row => userLoader.load(row.toID))
400+
}
397401
}
398402
})
399403
})
@@ -415,15 +419,15 @@ function createLoaders(authToken) {
415419
users: new DataLoader(ids => genUsers(authToken, ids)),
416420
cdnUrls: new DataLoader(rawUrls => genCdnUrls(authToken, rawUrls)),
417421
stories: new DataLoader(keys => genStories(authToken, keys)),
418-
};
422+
}
419423
}
420424

421425
// When handling an incoming web request:
422-
var loaders = createLoaders(request.query.authToken);
426+
const loaders = createLoaders(request.query.authToken)
423427

424428
// Then, within application logic:
425-
var user = await loaders.users.load(4);
426-
var pic = await loaders.cdnUrls.load(user.rawPicUrl);
429+
const user = await loaders.users.load(4)
430+
const pic = await loaders.cdnUrls.load(user.rawPicUrl)
427431
```
428432

429433
Creating an object where each key is a `DataLoader` is one common pattern which
@@ -438,19 +442,21 @@ value. If the same user is loaded by both keys, then it may be useful to fill
438442
both caches when a user is loaded from either source:
439443

440444
```js
441-
let userByIDLoader = new DataLoader(ids => genUsersByID(ids).then(users => {
445+
const userByIDLoader = new DataLoader(async ids => {
446+
const users = await genUsersByID(ids)
442447
for (let user of users) {
443-
usernameLoader.prime(user.username, user);
448+
usernameLoader.prime(user.username, user)
444449
}
445-
return users;
446-
}));
450+
return users
451+
})
447452

448-
let usernameLoader = new DataLoader(names => genUsernames(names).then(users => {
453+
const usernameLoader = new DataLoader(async names => {
454+
const users = await genUsernames(names)
449455
for (let user of users) {
450-
userByIDLoader.prime(user.id, user);
456+
userByIDLoader.prime(user.id, user)
451457
}
452-
return users;
453-
}));
458+
return users
459+
})
454460
```
455461

456462

examples/CouchDB.md

+9-11
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@ This example uses the [nano][] CouchDB client which offers a `fetch` method
88
supporting the bulk document API.
99

1010
```js
11-
var DataLoader = require('dataloader');
12-
var nano = require('nano');
11+
const DataLoader = require('dataloader');
12+
const nano = require('nano');
1313

14-
var couch = nano('http://localhost:5984');
14+
const couch = nano('http://localhost:5984');
1515

16-
var userDB = couch.use('users');
17-
var userLoader = new DataLoader(keys => new Promise((resolve, reject) => {
16+
const userDB = couch.use('users');
17+
const userLoader = new DataLoader(keys => new Promise((resolve, reject) => {
1818
userDB.fetch({ keys: keys }, (error, docs) => {
1919
if (error) {
2020
return reject(error);
@@ -25,12 +25,10 @@ var userLoader = new DataLoader(keys => new Promise((resolve, reject) => {
2525

2626
// Usage
2727

28-
var promise1 = userLoader.load('8fce1902834ac6458e9886fa7f89c0ef');
29-
var promise2 = userLoader.load('00a271787f89c0ef2e10e88a0c00048b');
30-
31-
Promise.all([ promise1, promise2 ]).then(([ user1, user2]) => {
32-
console.log(user1, user2);
33-
});
28+
const promise1 = userLoader.load('8fce1902834ac6458e9886fa7f89c0ef');
29+
const promise2 = userLoader.load('00a271787f89c0ef2e10e88a0c00048b');
30+
const [ user1, user2 ] = await Promise.all([ promise1, promise2 ])
31+
console.log(user1, user2);
3432
```
3533

3634
[nano]: https://github.com/dscape/nano

examples/GoogleDatastore.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,16 @@ const Datastore = require('@google-cloud/datastore');
1010

1111
const datastore = new Datastore();
1212

13-
const datastoreLoader = new DataLoader(keys =>
14-
datastore.get(keys).then(results => {
13+
const datastoreLoader = new DataLoader(async keys => {
14+
const results = await datastore.get(keys)
1515
// Sort resulting entities by the keys they were requested with.
1616
const entities = results[0];
1717
const entitiesByKey = {};
1818
entities.forEach(entity => {
1919
entitiesByKey[JSON.stringify(entity[datastore.KEY])] = entity;
2020
});
2121
return keys.map(key => entitiesByKey[JSON.stringify(key)] || null);
22-
}),
22+
},
2323
{
2424
// Datastore complex keys need to be converted to a string for use as cache keys
2525
cacheKeyFn: key => JSON.stringify(key),

examples/Knex.md

+5-5
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const db = require('./db'); // an instance of Knex client
1414

1515
// The list of data loaders
1616

17-
const data = {
17+
const loaders = {
1818
user: new DataLoader(ids => db.table('users')
1919
.whereIn('id', ids).select()
2020
.then(rows => ids.map(id => rows.find(x => x.id === id)))),
@@ -30,10 +30,10 @@ const data = {
3030

3131
// Usage
3232

33-
Promise.all([
34-
data.user.load('1234'),
35-
data.storiesByUserId.load('1234'),
36-
]).then(([user, stories]) => {/* ... */});
33+
const [user, stories] = await Promise.all([
34+
loaders.user.load('1234'),
35+
loaders.storiesByUserId.load('1234'),
36+
])
3737
```
3838

3939
For a complete example visit [kriasoft/nodejs-api-starter][nsk].

examples/Redis.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ with DataLoader.
77
Here we build an example Redis DataLoader using [node_redis][].
88

99
```js
10-
var DataLoader = require('dataloader');
11-
var redis = require('redis');
10+
const DataLoader = require('dataloader');
11+
const redis = require('redis');
1212

13-
var client = redis.createClient();
13+
const client = redis.createClient();
1414

15-
var redisLoader = new DataLoader(keys => new Promise((resolve, reject) => {
15+
const redisLoader = new DataLoader(keys => new Promise((resolve, reject) => {
1616
client.mget(keys, (error, results) => {
1717
if (error) {
1818
return reject(error);

0 commit comments

Comments
 (0)