Class: Seatsio::HttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/seatsio/httpClient.rb

Instance Method Summary collapse

Constructor Details

#initialize(secret_key, workspace_key, base_url) ⇒ HttpClient

Returns a new instance of HttpClient.



9
10
11
12
13
# File 'lib/seatsio/httpClient.rb', line 9

def initialize(secret_key, workspace_key, base_url)
  @secret_key = Base64.encode64(secret_key)
  @workspace_key = workspace_key
  @base_url = base_url
end

Instance Method Details

#delete(endpoint) ⇒ Object



82
83
84
# File 'lib/seatsio/httpClient.rb', line 82

def delete(endpoint)
  execute(:delete, endpoint, {})
end

#execute(*args) ⇒ 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
50
# File 'lib/seatsio/httpClient.rb', line 15

def execute(*args)
  begin
    headers = { :Authorization => "Basic #{@secret_key}" }
    unless @workspace_key.nil?
      headers[:'X-Workspace-Key'] = @workspace_key
    end
    if args[2].include? :params
      headers[:params] = args[2][:params]
    end

    url = "#{@base_url}/#{args[1]}"

    request_options = { method: args[0], url: url, headers: headers }

    if args[0] == :post
      args[2].delete :params
      request_options[:payload] = args[2].to_json
    end

    response = execute_with_retries(request_options)

    # If RAW
    if args[3]
      return response
    end
    JSON.parse(response) unless response.empty?
  rescue RestClient::NotFound => e
    raise Exception::NotFoundException.new(e.response)
  rescue RestClient::ExceptionWithResponse => e
    raise Exception::SeatsioException.new(e.response)
  rescue RestClient::Exceptions::Timeout
    raise Exception::SeatsioException.new("Timeout ERROR")
  rescue SocketError
    raise Exception::SeatsioException.new("Failed to connect to backend")
  end
end

#execute_with_retries(request_options) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/seatsio/httpClient.rb', line 52

def execute_with_retries(request_options)
  retry_count = 0
  while true
    begin
      return RestClient::Request.execute(request_options)
    rescue RestClient::ExceptionWithResponse => e
      if e.response.code != 429 || retry_count >= 5
        raise e
      else
        wait_time = (2 ** (retry_count + 2)) / 10.0
        sleep(wait_time)
        retry_count += 1
      end
    end
  end
end

#get(endpoint, params = {}) ⇒ Object



73
74
75
76
# File 'lib/seatsio/httpClient.rb', line 73

def get(endpoint, params = {})
  payload = { :params => params }
  execute(:get, endpoint, payload)
end

#get_raw(endpoint, params = {}) ⇒ Object



69
70
71
# File 'lib/seatsio/httpClient.rb', line 69

def get_raw(endpoint, params = {})
  execute(:get, endpoint, params, true)
end

#post(endpoint, payload = {}) ⇒ Object



78
79
80
# File 'lib/seatsio/httpClient.rb', line 78

def post(endpoint, payload = {})
  execute(:post, endpoint, payload)
end