-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path08 - DataLoader.js
99 lines (91 loc) · 2.05 KB
/
08 - DataLoader.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* Lesson 08 - DataLoader
*
* We've now built a functional DataLoader step-by-step showing exactly
* why each step is needed. This API is very close to the official DataLoader
* package maintained by the GraphQL Foundation
*
* Which we can install with `npm install --save dataloader`
*
* Import the DataLoader package
* const dataloader = require dataloader
*
* Delete the big class we wrote
*
* And now we're using the DataLoader package for our userLoader
*
* Test the code again, and it looks like all the results are still returning
* correctly
*
query {
posts {
id
title
author {
id
name
}
}
}
*
*/
const { ApolloServer, gql } = require("apollo-server");
const DataLoader = require("dataloader");
const sql = require("knex")({
client: "pg",
connection: {
host: "127.0.0.1",
port: 5432,
user: "postgres",
password: "password",
database: "postgres",
},
});
// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
const typeDefs = gql`
type Query {
posts: [Post]
}
type Post {
id: String
title: String
author: User
}
type User {
id: String
name: String
}
`;
const resolvers = {
Query: {
posts() {
// Executes once per query
console.log("SELECT * from posts");
return sql("posts").select("*");
},
},
Post: {
async author(post, args, { userLoader }) {
// Executes once per post per query
return userLoader.load(post.author_id);
},
},
};
const server = new ApolloServer({
typeDefs,
resolvers,
async context() {
return {
userLoader: new DataLoader((keys) => {
console.log(`SELECT * from users WHERE id in (${keys.join(",")})`);
return sql.select("*").from("users").whereIn("id", keys);
}),
};
},
});
// The `listen` method launches a web server.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});