-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathreviews.js
113 lines (104 loc) · 2.38 KB
/
reviews.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
const { ApolloServer } = require('apollo-server')
const { buildFederatedSchema } = require('@apollo/federation')
const { post } = require('httpie')
const { parse } = require('graphql')
const typeDefs = /* GraphQL */ `
type Review @key(fields: "id") {
id: ID!
body: String
author: User @provides(fields: "username")
product: Product
}
extend type User @key(fields: "id") {
id: ID! @external
username: String @external
reviews: [Review]
}
extend type Product @key(fields: "upc") {
upc: String! @external
reviews: [Review]
}
`
async function main() {
// Push schema to registry
await post(`http://localhost:3000/schema/push`, {
body: {
typeDefs: typeDefs,
graphName: 'my_graph',
serviceName: 'reviews',
routingUrl: 'http://localhost:4002/graphql',
},
})
startServer()
}
function startServer() {
const resolvers = {
Review: {
author(review) {
return { __typename: 'User', id: review.authorID }
},
},
User: {
reviews(user) {
return reviews.filter((review) => review.authorID === user.id)
},
numberOfReviews(user) {
return reviews.filter((review) => review.authorID === user.id).length
},
username(user) {
const found = usernames.find((username) => username.id === user.id)
return found ? found.username : null
},
},
Product: {
reviews(product) {
return reviews.filter((review) => review.product.upc === product.upc)
},
},
}
const server = new ApolloServer({
schema: buildFederatedSchema([
{
typeDefs: parse(typeDefs),
resolvers,
},
]),
})
server.listen({ port: 4002 }).then(({ url }) => {
console.log(`🚀 Server ready at ${url}`)
})
const usernames = [
{ id: '1', username: '@ada' },
{ id: '2', username: '@complete' },
]
const reviews = [
{
id: '1',
authorID: '1',
product: { upc: '1' },
body: 'Love it!',
},
{
id: '2',
authorID: '1',
product: { upc: '2' },
body: 'Too expensive.',
},
{
id: '3',
authorID: '2',
product: { upc: '3' },
body: 'Could be better.',
},
{
id: '4',
authorID: '2',
product: { upc: '1' },
body: 'Prefer something else.',
},
]
}
main().catch((err) => {
console.error(err)
process.exit(1)
})