Class: Elessar::ConnectionManager

Inherits:
Object
  • Object
show all
Defined in:
lib/elessar/connection_manager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = Elessar.config) ⇒ ConnectionManager



7
8
9
10
# File 'lib/elessar/connection_manager.rb', line 7

def initialize(config = Elessar.config)
  @config = config
  @active_connections = {}
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



5
6
7
# File 'lib/elessar/connection_manager.rb', line 5

def config
  @config
end

Instance Method Details

#authorization_headersObject



26
27
28
29
30
31
# File 'lib/elessar/connection_manager.rb', line 26

def authorization_headers
  headers = {
    "Authorization" => "Bearer #{Elessar.api_key}",
    "Content-Type" => "application/json",
  }
end

#connection_for(uri) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/elessar/connection_manager.rb', line 12

def connection_for(uri)
  u = URI.parse(uri)
  connection = @active_connections[[u.host, u.port]]

  if connection.nil?
    connection = create_connection(u)
    connection.start

    @active_connections[[u.host, u.port]] = connection
  end

  connection
end

#execute_request(method, uri, body: nil, headers: {}, query:, &block) ⇒ Object

Raises:

  • (ArgumentError)


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
75
76
77
# File 'lib/elessar/connection_manager.rb', line 33

def execute_request(method, uri, body: nil, headers: {}, query:, &block)
  raise ArgumentError, "method should be a symbol" unless method.is_a?(Symbol)
  raise ArgumentError, "uri should be a string" unless uri.is_a?(String)
  raise ArgumentError, "body should be a string" if body && !body.is_a?(String)
  raise ArgumentError, "headers should be a hash" if headers && !headers.is_a?(Hash)
  raise ArgumentError, "query should be a hash or string" if query && (!query.is_a?(Hash) and !query.is_a?(String))

  headers = headers.merge(authorization_headers)
  uri = Elessar.api_base + uri

  connection = connection_for(uri)

  u = URI.parse(uri)
  path = case query
    when String
      u.path + "?" + query
    when Hash
      u.path + "?" + URI.encode_www_form(query)
    else
      u.path
    end

  method_name = method.to_s.upcase
  has_response_body = method_name != "HEAD"
  request = Net::HTTPGenericRequest.new(
    method_name,
    (body ? true : false),
    has_response_body,
    path,
    headers
  )

  http_resp = begin
      retries ||= 0
      connection.request(request, body, &block)
    rescue
      retry if (retries += 1) < Elessar.max_network_retries
    end

  begin
    resp = ElessarResponse.from_net_http(http_resp)
  rescue JSON::ParserError
    raise general_api_error(http_resp.code.to_i, http_resp.body)
  end
end