-
Notifications
You must be signed in to change notification settings - Fork 0
/
n-plus-1.ts
82 lines (75 loc) · 1.83 KB
/
n-plus-1.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { dummyEndpoint } from "../lib/dummy-rest-api-sdk.js";
import { builder } from "~/builder";
const UserObject = builder.simpleObject("User", {
fields: (t) => ({
id: t.int({
nullable: false,
description: "The ID of the user",
}),
name: t.string({
description: "The name of the user",
nullable: false,
}),
}),
});
builder.objectField(UserObject, "posts", (t) =>
t.field({
type: [PostObject],
nullable: false,
resolve: async (user) => {
const posts = await dummyEndpoint.getUserPosts(user.id);
return posts;
},
})
// ** N+1 problem **
// Uncomment this to fix the N+1 problem
// Solved by: Batching user ids and fetching posts in a single request
//
// t.loadableGroup({
// type: PostObject,
// load: (ids: number[]) => dummyEndpoint.getPostsByUserIds(ids),
// group: (post) => post.userId,
// resolve: (user) => user.id,
// })
);
const PostObject = builder.simpleObject("Post", {
fields: (t) => ({
id: t.int({
nullable: false,
}),
title: t.string({
description: "The title of the post",
nullable: false,
}),
content: t.string({
description: "The content of the post",
nullable: false,
}),
userId: t.int({
description: "The user ID of the post",
nullable: false,
}),
}),
});
builder.objectField(PostObject, "user", (t) =>
t.field({
type: UserObject,
nullable: false,
resolve: async (post) => {
const user = await dummyEndpoint.getUserById(post.userId);
return user;
},
})
);
builder.queryField("users", (t) =>
t.field({
type: [UserObject],
nullable: false,
resolve: async () => {
const users = await dummyEndpoint.getUsers();
return users;
},
})
);
builder.queryType({});
export const schema = builder.toSchema();