Method: GraphQL::Client::HTTP#execute

Defined in:
lib/graphql/client/http.rb

#execute(document:, operation_name: nil, variables: {}, context: {}) ⇒ Object

Public: Make an HTTP request for GraphQL query.

Implements Client’s “execute” adapter interface.

document - The Query GraphQL::Language::Nodes::Document operation_name - The String operation definition name variables - Hash of query variables context - An arbitrary Hash of values which you can access

Returns { “data” => … , “errors” => … } Hash.


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/graphql/client/http.rb', line 58

def execute(document:, operation_name: nil, variables: {}, context: {})
  request = Net::HTTP::Post.new(uri.request_uri)

  request.basic_auth(uri.user, uri.password) if uri.user || uri.password

  request["Accept"] = "application/json"
  request["Content-Type"] = "application/json"
  headers(context).each { |name, value| request[name] = value }

  body = {}
  body["query"] = document.to_query_string
  body["variables"] = variables if variables.any?
  body["operationName"] = operation_name if operation_name
  request.body = JSON.generate(body)

  response = connection.request(request)
  case response
  when Net::HTTPOK, Net::HTTPBadRequest
    JSON.parse(response.body)
  else
    { "errors" => [{ "message" => "#{response.code} #{response.message}" }] }
  end
end