Class: GraphQL::Hive::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql-hive/client.rb

Overview

API client

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Client



10
11
12
# File 'lib/graphql-hive/client.rb', line 10

def initialize(options)
  @options = options
end

Instance Method Details

#build_request(uri, body) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/graphql-hive/client.rb', line 50

def build_request(uri, body)
  request = Net::HTTP::Post.new(uri.request_uri)
  request["Authorization"] = "Bearer #{@options[:token]}"
  request["X-Usage-API-Version"] = "2"
  request["content-type"] = "application/json"
  request["User-Agent"] = "Hive@#{Graphql::Hive::VERSION}"
  request["graphql-client-name"] = "Hive Ruby Client"
  request["graphql-client-version"] = Graphql::Hive::VERSION
  request.body = JSON.generate(body)
  request
end

#extract_error_details(response) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/graphql-hive/client.rb', line 62

def extract_error_details(response)
  parsed_body = JSON.parse(response.body)
  return unless parsed_body.is_a?(Hash) && parsed_body["errors"].is_a?(Array)
  parsed_body["errors"].map { |error| "{ path: #{error["path"]}, message: #{error["message"]} }" }.join(", ")
rescue JSON::ParserError
  "Could not parse response from Hive"
end

#send(path, body, _log_type) ⇒ Object



14
15
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
# File 'lib/graphql-hive/client.rb', line 14

def send(path, body, _log_type)
  path = path.to_s
  if path == "/usage" && @options[:target] && @options[:target] != ""
    path = "/usage/#{@options[:target]}"
  end
  uri =
    URI::HTTP.build(
      scheme: (@options[:port].to_s == "443") ? "https" : "http",
      host: @options[:endpoint] || "app.graphql-hive.com",
      port: @options[:port] || "443",
      path: path
    )

  http = setup_http(uri)
  request = build_request(uri, body)
  response = http.request(request)

  code = response.code.to_i
  if code >= 400 && code < 500
    error_message = "Unsuccessful response: #{response.code} - #{response.message}"
    @options[:logger].warn("#{error_message} #{extract_error_details(response)}")
  end

  @options[:logger].debug(response.inspect)
  @options[:logger].debug(response.body.inspect)
rescue => e
  @options[:logger].fatal("Failed to send data: #{e}")
end

#setup_http(uri) ⇒ Object



43
44
45
46
47
48
# File 'lib/graphql-hive/client.rb', line 43

def setup_http(uri)
  http = ::Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = @options[:port].to_s == "443"
  http.read_timeout = 2
  http
end