forked from Gusto/apollo-federation-ruby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphql_server.rb
78 lines (66 loc) · 1.68 KB
/
graphql_server.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
# frozen_string_literal: true
require 'rack'
require 'json'
require 'graphql'
require 'pry-byebug'
require 'apollo-federation'
require 'optparse'
require 'webrick'
class BaseField < GraphQL::Schema::Field
include ApolloFederation::Field
end
class BaseObject < GraphQL::Schema::Object
include ApolloFederation::Object
field_class BaseField
end
class GraphQLServer
def self.run(schema, options = {})
test_mode = false
handler_options = options.dup
OptionParser.new do |opts|
opts.on('--test', 'Run in test mode') do |test|
test_mode = test
if test
handler_options.merge!(
Logger: ::WEBrick::Log.new($stderr, ::WEBrick::Log::ERROR),
AccessLog: [],
)
end
end
end.parse!
Rack::Handler::WEBrick.run(GraphQLServer.new(schema), **handler_options) do
if test_mode
$stdout.puts '_READY_'
$stdout.flush
end
end
end
def initialize(schema)
self.schema = schema
end
def call(env)
req = Rack::Request.new(env)
req_vars = JSON.parse(req.body.read)
query = req_vars['query']
operation_name = req_vars['operationName']
vars = req_vars['variables'] || {}
graphql_debugging = {
query: query,
operationName: operation_name,
vars: vars,
schema: schema,
}
puts graphql_debugging.inspect
result = schema.execute(
query,
operation_name: operation_name,
variables: vars,
context: {
tracing_enabled: ApolloFederation::Tracing.should_add_traces(env),
},
)
['200', { 'Content-Type' => 'application/json' }, [JSON.dump(result.to_h)]]
end
private
attr_accessor :schema
end