Skip to content

Commit 68a2a2e

Browse files
committed
README example of loading by alt keys
1 parent 77375f4 commit 68a2a2e

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,8 @@ var UserType = new GraphQLObjectType({
273273

274274
## Common Patterns
275275

276+
### Creating a new DataLoader per request.
277+
276278
In many applications, a web server using DataLoader serves requests to many
277279
different users with different access permissions. It may be dangerous to use
278280
one cache across many users, and is encouraged to create a new cache
@@ -299,6 +301,28 @@ Creating an object where each key is a `DataLoader` is also a common pattern.
299301
This provides a single value to pass around to code which needs to perform
300302
data loading, such as part of the `rootValue` in a [graphql-js][] request.
301303

304+
### Loading by alternative keys.
305+
306+
Occasionally, some kind of value can be accessed in multiple ways. For example,
307+
perhaps a "User" type can be loaded not only by an "id" but also by a "username"
308+
value. If the same user is loaded by both keys, then it may be useful to fill
309+
both caches when a user is loaded from either source:
310+
311+
```js
312+
let userByIDLoader = new DataLoader(ids => genUsersByID(ids).then(users => {
313+
for (let user of users) {
314+
usernameLoader.prime(user.username, user);
315+
}
316+
return users;
317+
}));
318+
319+
let usernameLoader = new DataLoader(names => genUsernames(names).then(users => {
320+
for (let user of users) {
321+
userByIDLoader.prime(user.id, user);
322+
}
323+
return users;
324+
}));
325+
```
302326

303327
## Custom Caches
304328

0 commit comments

Comments
 (0)