forked from Gusto/apollo-federation-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reviews.rb
110 lines (90 loc) · 2.17 KB
/
reviews.rb
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
# frozen_string_literal: true
require_relative './graphql_server'
# 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]
# }
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.',
},
].freeze
USERNAMES = [
{ id: '1', username: '@ada' },
{ id: '2', username: '@complete' },
].freeze
class Review < BaseObject
key fields: :id
field :id, ID, null: false
field :body, String, null: true
field :author, 'User', null: true, provides: { fields: :username }
field :product, 'Product', null: true
def author
{ __typename: 'User', id: object[:authorID] }
end
end
class User < BaseObject
key fields: :id
extend_type
field :id, ID, null: false, external: true
field :username, String, null: true, external: true
field :reviews, [Review], null: true
def reviews
REVIEWS.select { |review| review[:authorID] == object[:id] }
end
def username
found = USERNAMES.find { |username| username[:id] == object[:id] }
found ? found[:username] : nil
end
end
class Product < BaseObject
key fields: :upc
extend_type
field :upc, String, null: false, external: true
field :reviews, [Review], null: true
def reviews
REVIEWS.select { |review| review[:product][:upc] == object[:upc] }
end
end
class ReviewSchema < GraphQL::Schema
if Gem::Version.new(GraphQL::VERSION) < Gem::Version.new('1.12.0')
use GraphQL::Execution::Interpreter
use GraphQL::Analysis::AST
end
use ApolloFederation::Tracing
include ApolloFederation::Schema
orphan_types User, Review, Product
end
GraphQLServer.run(ReviewSchema, Port: 5002)