-
Notifications
You must be signed in to change notification settings - Fork 15
/
server-review.js
120 lines (101 loc) · 2.28 KB
/
server-review.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
* Review service
*/
const { ApolloServer, gql } = require('apollo-server');
const { buildSubgraphSchema } = require('@apollo/federation');
const { connectionFromArray } = require('graphql-relay');
const { toRecords } = require('./util');
const GraphQLNode = require('./graphql-node');
const { toId } = GraphQLNode;
const REVIEWS = [
{
id: toId('Review', '1'),
body: `It's OK!`,
rating: 5,
node: { id: toId('Product', '1') },
},
{
id: toId('Review', '2'),
body: `It's pretty good!`,
rating: 2,
node: { id: toId('Product', '1') },
},
{
id: toId('Review', '3'),
body: `It's really bad`,
rating: 1,
node: { id: toId('Product', '1') },
},
];
const REVIEWS_MAP = toRecords(REVIEWS);
const typeDefs = gql`
type Query {
node(id: ID!): Node
review(id: ID!): Review
reviews(ids: [ID!]): [Review]
}
type Review implements Node @key(fields: "id") {
id: ID!
body: String!
rating: Int
node: Node
}
extend type Product implements Node @key(fields: "id") {
id: ID! @external
reviews(
after: String
first: Int
before: String
last: Int
): ReviewConnection
}
type ReviewConnection {
pageInfo: PageInfo!
edges: [ReviewEdge]
}
type ReviewEdge {
node: Review
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
`;
const nodeTypes = new Set(['Review']);
const resolvers = {
Query: {
node(_, { id }) {
const [typename] = GraphQLNode.fromId(id);
if (!nodeTypes.has(typename)) {
throw new Error(`Invalid node ID "${id}"`);
}
return REVIEWS_MAP[id];
},
review(_, { id }) {
return REVIEWS_MAP[id];
},
reviews(_, { ids }) {
if (!ids) {
return REVIEWS;
}
return ids.map(id => REVIEWS_MAP[id] || null);
},
},
Review: {
__resolveReference(review) {
return REVIEWS_MAP[review.id];
},
},
Product: {
reviews(product, args) {
const data = REVIEWS.filter(({ node }) => node && node.id === product.id);
return connectionFromArray(data, args);
},
},
};
exports.server = new ApolloServer({
schema: buildSubgraphSchema([{ typeDefs, resolvers }, GraphQLNode]),
});