-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver-product.js
110 lines (90 loc) · 2.11 KB
/
server-product.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
/**
* Product 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 PRODUCTS = [
{
id: toId('Product', '1'),
name: 'My little product',
related: [toId('Product', '2'), toId('Product', '3')],
},
{
id: toId('Product', '2'),
name: 'My other product',
related: [toId('Product', '1')],
},
{
id: toId('Product', '3'),
name: 'My third product',
},
];
const PRODUCTS_MAP = toRecords(PRODUCTS);
const typeDefs = gql`
type Query {
node(id: ID!): Node
product(id: ID!): Product
products(ids: [ID!]): [Product]
}
type Product implements Node @key(fields: "id") {
id: ID!
name: String!
related(
after: String
first: Int
before: String
last: Int
): ProductConnection
}
type ProductConnection {
pageInfo: PageInfo!
edges: [ProductEdge]
}
type ProductEdge {
node: Product
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
`;
const nodeTypes = new Set(['Product']);
const resolvers = {
Query: {
node(_, { id }) {
const [typename] = GraphQLNode.fromId(id);
if (!nodeTypes.has(typename)) {
throw new Error(`Invalid node ID "${id}"`);
}
return PRODUCTS_MAP[id];
},
product(_, { id }) {
return PRODUCTS_MAP[id];
},
products(_, { ids }) {
if (!ids) {
return PRODUCTS;
}
return ids.map(id => PRODUCTS_MAP[id] || null);
},
},
Product: {
related({ related }, args) {
const data = related ? related.map(id => PRODUCTS_MAP[id]) : [];
return connectionFromArray(data, args);
},
__resolveReference(product) {
return PRODUCTS_MAP[product.id];
},
},
};
exports.server = new ApolloServer({
schema: buildSubgraphSchema([{ typeDefs, resolvers }, GraphQLNode]),
});