Class: RackGraphql::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/rack_graphql/middleware.rb

Constant Summary collapse

DEFAULT_STATUS_CODE =
200
DEFAULT_ERROR_STATUS_CODE =
500
NULL_BYTE =
'\u0000'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(schema:, app_name: nil, context_handler: nil, logger: nil, log_exception_backtrace: RackGraphql.log_exception_backtrace, re_raise_exceptions: false, error_status_code_map: {}) ⇒ Middleware

Returns a new instance of Middleware.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rack_graphql/middleware.rb', line 7

def initialize(
  schema:,
  app_name: nil,
  context_handler: nil,
  logger: nil,
  log_exception_backtrace: RackGraphql.log_exception_backtrace,
  re_raise_exceptions: false,
  error_status_code_map: {}
)

  @schema = schema
  @app_name = app_name
  @context_handler = context_handler || ->(_) {}
  @logger = logger
  @log_exception_backtrace = log_exception_backtrace
  @re_raise_exceptions = re_raise_exceptions
  @error_status_code_map = error_status_code_map
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/rack_graphql/middleware.rb', line 26

def call(env)
  return [406, {}, []] unless post_request?(env)

  params = post_data(env)

  return [400, {}, []] unless params.is_a?(Hash)

  variables = ensure_hash(params['variables'])
  operation_name = params['operationName']
  context = context_handler.call(env)

  log("Executing with params: #{params.inspect}, operationName: #{operation_name}, variables: #{variables.inspect}")
  result = execute(params: params, operation_name: operation_name, variables: variables, context: context)

  [
    response_status(result),
    response_headers(result),
    [response_body(result)]
  ]
rescue AmbiguousParamError => e
  exception_string = dump_exception(e)
  log(exception_string)
  env[Rack::RACK_ERRORS].puts(exception_string)
  env[Rack::RACK_ERRORS].flush
  [
    400,
    { 'Content-Type' => 'application/json' },
    [Oj.dump({})]
  ]
rescue StandardError, LoadError, SyntaxError => e
  # To respect the graphql spec, all errors need to be returned as json.
  # By default exceptions are not re-raised,
  # so they cannot be caught by error tracking rack middlewares.
  # You can change this behavior via `re_raise_exceptions` argument.
  exception_string = dump_exception(e)
  log(exception_string)

  raise e if re_raise_exceptions

  env[Rack::RACK_ERRORS].puts(exception_string)
  env[Rack::RACK_ERRORS].flush
  [
    error_status_code_map[e.class] || DEFAULT_ERROR_STATUS_CODE,
    { 'Content-Type' => 'application/json' },
    [Oj.dump('errors' => [exception_hash(e)])]
  ]
ensure
  ActiveRecord::Base.clear_active_connections! if defined?(ActiveRecord::Base)
end