22title : 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
66performance issues related to the N+1 problem: a pattern that
77results in many unnecessary database or service calls,
88especially in nested query structures.
@@ -69,7 +69,8 @@ when setting up a GraphQL HTTP server such as [express-graphql](https://github.c
6969Suppose each ` Post ` has an ` authorId ` , and you have a ` getUsersByIds(ids) `
7070function that can fetch multiple users in a single call:
7171
72- ``` js
72+ { /* prettier-ignore */ }
73+ ``` js {14-17,37}
7374import {
7475 graphql ,
7576 GraphQLObjectType ,
@@ -81,6 +82,15 @@ import {
8182import DataLoader from ' dataloader' ;
8283import { 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+
8494const UserType = new GraphQLObjectType ({
8595 name: ' User' ,
8696 fields : () => ({
@@ -114,15 +124,6 @@ const QueryType = new GraphQLObjectType({
114124});
115125
116126const 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
128129With this setup, all ` .load(authorId) ` calls are automatically collected and batched
0 commit comments