Class: Provide::ApiClient

Inherits:
Object
  • Object
show all
Defined in:
lib/provide-ruby/api_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(scheme = API_SCHEME, host = API_HOST, path = 'api/', token = nil) ⇒ ApiClient

Returns a new instance of ApiClient.



15
16
17
18
# File 'lib/provide-ruby/api_client.rb', line 15

def initialize(scheme = API_SCHEME, host = API_HOST, path = 'api/', token = nil)
  @base_url = "#{scheme}://#{host}/#{path}"
  @token = token
end

Instance Attribute Details

#base_urlObject (readonly)

Returns the value of attribute base_url.



13
14
15
# File 'lib/provide-ruby/api_client.rb', line 13

def base_url
  @base_url
end

#tokenObject (readonly)

Returns the value of attribute token.



13
14
15
# File 'lib/provide-ruby/api_client.rb', line 13

def token
  @token
end

Instance Method Details

#delete(uri, params = nil) ⇒ Object



32
33
34
# File 'lib/provide-ruby/api_client.rb', line 32

def delete(uri, params = nil)
  send_request(:delete, uri, params || {})
end

#get(uri, params = nil) ⇒ Object



20
21
22
# File 'lib/provide-ruby/api_client.rb', line 20

def get(uri, params = nil)
  send_request(:get, uri, params || {})
end

#post(uri, params = nil) ⇒ Object



24
25
26
# File 'lib/provide-ruby/api_client.rb', line 24

def post(uri, params = nil)
  send_request(:post, uri, params || {})
end

#put(uri, params = nil) ⇒ Object



28
29
30
# File 'lib/provide-ruby/api_client.rb', line 28

def put(uri, params = nil)
  send_request(:put, uri, params || {})
end

#send_request(method, uri, params = nil, headers = nil) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/provide-ruby/api_client.rb', line 36

def send_request(method, uri, params = nil, headers = nil)
  attempts = 0

  begin
    params = [:post, :put, :patch].include?(method.to_s.downcase.to_sym) ? { body: JSON.dump(params) } : { params: params }
    headers = default_headers.merge(headers || {})
    headers['Content-Type'] = 'application/json' if [:post, :put, :patch].include?(method.to_s.downcase.to_sym)
    params.merge!(headers: headers, timeout: API_TIMEOUT)
    params.merge!(ssl_verifypeer: false, ssl_verifyhost: 0) if API_PROMISCUOUS_MODE
    Typhoeus.send(method.to_s.downcase.to_sym, "#{base_url}#{uri}", params)
  rescue
    attempts = attempts + 1
    retry if attempts < API_MAX_ATTEMPTS
  end
end