Class: HttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/tacklebox/apis/http_client.rb

Instance Method Summary collapse

Constructor Details

#initialize(api_key) ⇒ HttpClient

Returns a new instance of HttpClient.



8
9
10
11
12
13
# File 'lib/tacklebox/apis/http_client.rb', line 8

def initialize(api_key)
  @headers = {
    "x-api-key" => api_key,
    "Content-Type" => "application/json",
  }
end

Instance Method Details

#send(request) ⇒ Object



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
42
43
44
45
46
47
48
49
# File 'lib/tacklebox/apis/http_client.rb', line 15

def send(request)
  conn = Faraday.new(
    url: request.base_url,
    headers: @headers,
    request: { timeout: MAX_TIMEOUT }
  )
  
  while request.attempt <= MAX_RETRY_ATTEMPTS
    begin
      case request.method
      when "GET"
        response = conn.get(request.path)
        return JSON.parse(response.body)
      when "POST"
        response = conn.post(request.path) do |req|
          req.body = request.data.to_json
        end
        return JSON.parse(response.body)
      when "PUT"
        response = conn.put(request.path) do |req|
          req.body = request.data.to_json
        end
        return JSON.parse(response.body)
      when "DELETE"
        response = conn.delete(request.path)
        return JSON.parse(response.body)
      end
    rescue Faraday::ConnectionFailed => e
      puts "Connection failed: #{e}"
      exit 1
    end
    
    request.attempt += 1;
  end
end