Class: GraphQL::Client::Adapters::HTTPAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql_client/adapters/http_adapter.rb

Constant Summary collapse

JSON_MIME_TYPE =
'application/json'.freeze
DEFAULT_HEADERS =
{ 'Accept' => JSON_MIME_TYPE, 'Content-Type' => JSON_MIME_TYPE }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ HTTPAdapter

Returns a new instance of HTTPAdapter.



12
13
14
# File 'lib/graphql_client/adapters/http_adapter.rb', line 12

def initialize(config)
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



10
11
12
# File 'lib/graphql_client/adapters/http_adapter.rb', line 10

def config
  @config
end

Instance Method Details

#request(query, operation_name: nil, variables: {}) ⇒ Object



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
# File 'lib/graphql_client/adapters/http_adapter.rb', line 16

def request(query, operation_name: nil, variables: {})
  req = build_request(query, operation_name: operation_name, variables: variables)

  http_options = {
    use_ssl: https?,
    open_timeout: config.open_timeout,
    read_timeout: config.read_timeout
  }

  # IMPORTANT: open_timeout is only respected when it's supplied as part of the options
  # when you call Net::HTTP.start. It is not respected when it's set inside the block of
  # Net::HTTP.start (i.e. http.open_timeout = 1)
  response = Net::HTTP.start(config.url.hostname, config.url.port, http_options) do |http|
    http.request(req)
  end

  case response
  when Net::HTTPOK
    puts "Response body: \n#{JSON.pretty_generate(JSON.parse(response.body))}" if debug?
    Response.new(response.body)
  else
    raise ClientError, response
  end
rescue Net::OpenTimeout
  raise OpenTimeoutError, "timeout while waiting for a connection"
rescue Net::ReadTimeout
  raise ReadTimeoutError, "timeout while waiting for a response"
end