2
2
title : Solving the N+1 Problem with `DataLoader`
3
3
---
4
4
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
6
6
performance issues related to the N+1 problem: a pattern that
7
7
results in many unnecessary database or service calls,
8
8
especially in nested query structures.
@@ -69,7 +69,8 @@ when setting up a GraphQL HTTP server such as [express-graphql](https://github.c
69
69
Suppose each ` Post ` has an ` authorId ` , and you have a ` getUsersByIds(ids) `
70
70
function that can fetch multiple users in a single call:
71
71
72
- ``` js
72
+ { /* prettier-ignore */ }
73
+ ``` js {14-17,37}
73
74
import {
74
75
graphql ,
75
76
GraphQLObjectType ,
@@ -81,6 +82,15 @@ import {
81
82
import DataLoader from ' dataloader' ;
82
83
import { getPosts , getUsersByIds } from ' ./db.js' ;
83
84
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
+
84
94
const UserType = new GraphQLObjectType ({
85
95
name: ' User' ,
86
96
fields : () => ({
@@ -114,15 +124,6 @@ const QueryType = new GraphQLObjectType({
114
124
});
115
125
116
126
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
- }
126
127
```
127
128
128
129
With this setup, all ` .load(authorId) ` calls are automatically collected and batched
0 commit comments