2
2
require 'json'
3
3
require 'rack'
4
4
5
- class GraphqlServer
6
- class InvalidRequestTypeError < Exception ; end ;
5
+ class GraphQLServer
6
+ class InvalidRequestType < Exception ; end ;
7
7
class PostBodyMissing < Exception ; end ;
8
8
9
- # Initilizes GraphqlServer as a Rack app or middleware
9
+ # Initilizes GraphQLServer as a Rack app or middleware
10
10
#
11
11
# This Rack middleware (or app) implements a spec-compliant GraphQL server which can be queried from any GraphQL client.
12
12
# It can be used with a provided GraphQL schema or can build one from a type definition and a resolver hash.
13
13
#
14
14
# @param [Array<Object>] *args The first argument should be `app` when used as a middleware
15
- # @param String path Also for middleware, we will use path to determine when to process GraphQL, defaults to '/'
16
15
# @param String type_def A schema definition string, or a path to a file containing the definition
17
16
# @param Hash resolver A hash with callables for handling field resolution
18
17
# @param GraphQL::Schema schema Use this schema if `type_def` and `resolver` is nil
19
18
# @param Hash context
20
- def initialize ( *args , path : nil , type_def : nil , resolver : nil , schema : nil , context : nil )
19
+ def initialize ( *args , type_def : nil , resolver : nil , schema : nil , context : nil )
21
20
@app = args && args [ 0 ]
22
21
@context = context
23
- @path = ( @app && !path ) ? '/' : path
24
22
@schema = type_def && resolver ? GraphQL ::Schema . from_definition ( type_def , default_resolve : resolver ) : schema
25
23
end
26
24
@@ -30,19 +28,16 @@ def middleware?
30
28
31
29
def call ( env )
32
30
request = Rack ::Request . new ( env )
33
-
34
- # only resolve when url matches `path` if we're in a middleware
35
- return @app . call ( env ) if middleware? && @path != request . path_info
36
31
37
32
# graphql accepts GET and POST requests
38
- raise InvalidRequestTypeError unless request . get? || request . post?
33
+ raise InvalidRequestType unless request . get? || request . post?
39
34
40
35
payload = if request . get?
41
36
request . params
42
37
elsif request . post?
43
38
body = request . body . read
44
39
raise PostBodyMissing if body . empty?
45
- payload = JSON . parse ( body )
40
+ JSON . parse ( body )
46
41
end
47
42
48
43
response = @schema . execute (
@@ -53,7 +48,7 @@ def call(env)
53
48
) . to_json
54
49
55
50
[ 200 , { 'Content-Type' => 'application/json' , 'Content-Length' => response . bytesize . to_s } , [ response ] ]
56
- rescue InvalidRequestTypeError
51
+ rescue InvalidRequestType
57
52
# Method Not Allowed
58
53
[ 405 , { "Content-Type" => "text/html" } , [ "GraphQL Server supports only GET/POST requests" ] ]
59
54
rescue PostBodyMissing
0 commit comments