Class: GraphQLServer
- Inherits:
-
Object
- Object
- GraphQLServer
- Defined in:
- lib/graphql_server.rb
Defined Under Namespace
Classes: InvalidRequestType, PostBodyMissing
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(*args, type_def: nil, resolver: nil, schema: nil, context: nil) ⇒ GraphQLServer
constructor
Initilizes GraphQLServer as a Rack app or middleware.
- #middleware? ⇒ Boolean
Constructor Details
#initialize(*args, type_def: nil, resolver: nil, schema: nil, context: nil) ⇒ GraphQLServer
Initilizes GraphQLServer as a Rack app or middleware
This Rack middleware (or app) implements a spec-compliant GraphQL server which can be queried from any GraphQL client. It can be used with a provided GraphQL schema or can build one from a type definition and a resolver hash.
19 20 21 22 23 |
# File 'lib/graphql_server.rb', line 19 def initialize(*args, type_def: nil, resolver: nil, schema: nil, context: nil) @app = args && args[0] @context = context @schema = type_def && resolver ? GraphQL::Schema.from_definition(type_def, default_resolve: resolver) : schema end |
Instance Method Details
#call(env) ⇒ Object
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 |
# File 'lib/graphql_server.rb', line 29 def call(env) request = Rack::Request.new(env) # graphql accepts GET and POST requests raise InvalidRequestType unless request.get? || request.post? payload = if request.get? request.params elsif request.post? body = request.body.read raise PostBodyMissing if body.empty? JSON.parse(body) end response = @schema.execute( payload['query'], variables: payload['variables'], operation_name: payload['operationName'], context: @context, ).to_json [200, {'Content-Type' => 'application/json', 'Content-Length' => response.bytesize.to_s}, [response]] rescue InvalidRequestType # Method Not Allowed [405, {"Content-Type" => "text/html"}, ["GraphQL Server supports only GET/POST requests"]] rescue PostBodyMissing # Bad Request [400, {"Content-Type" => "text/html"}, ["POST body missing"]] end |
#middleware? ⇒ Boolean
25 26 27 |
# File 'lib/graphql_server.rb', line 25 def middleware? !@app.nil? end |