Skip to content

Commit e5ab7f7

Browse files
committed
Light editorial on #4383
1 parent d7b5f26 commit e5ab7f7

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

website/pages/docs/n1-dataloader.mdx

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
title: Solving the N+1 Problem with `DataLoader`
33
---
44

5-
When building a server with GraphQL.js, it's common to encounter
5+
When building your first server with GraphQL.js, it's common to encounter
66
performance issues related to the N+1 problem: a pattern that
77
results in many unnecessary database or service calls,
88
especially in nested query structures.
@@ -69,7 +69,8 @@ when setting up a GraphQL HTTP server such as [express-graphql](https://github.c
6969
Suppose each `Post` has an `authorId`, and you have a `getUsersByIds(ids)`
7070
function that can fetch multiple users in a single call:
7171

72-
```js
72+
{/* prettier-ignore */}
73+
```js {14-17,37}
7374
import {
7475
graphql,
7576
GraphQLObjectType,
@@ -81,6 +82,15 @@ import {
8182
import DataLoader from 'dataloader';
8283
import { getPosts, getUsersByIds } from './db.js';
8384

85+
function createContext() {
86+
return {
87+
userLoader: new DataLoader(async (userIds) => {
88+
const users = await getUsersByIds(userIds);
89+
return userIds.map(id => users.find(user => user.id === id));
90+
}),
91+
};
92+
}
93+
8494
const UserType = new GraphQLObjectType({
8595
name: 'User',
8696
fields: () => ({
@@ -114,15 +124,6 @@ const QueryType = new GraphQLObjectType({
114124
});
115125

116126
const schema = new GraphQLSchema({ query: QueryType });
117-
118-
function createContext() {
119-
return {
120-
userLoader: new DataLoader(async (userIds) => {
121-
const users = await getUsersByIds(userIds);
122-
return userIds.map(id => users.find(user => user.id === id));
123-
}),
124-
};
125-
}
126127
```
127128

128129
With this setup, all `.load(authorId)` calls are automatically collected and batched

0 commit comments

Comments
 (0)