Module: Onfleet

Defined in:
lib/utils.rb,
lib/onfleet.rb,
lib/configuration.rb,
lib/resources/hubs.rb,
lib/resources/tasks.rb,
lib/resources/teams.rb,
lib/errors/http_error.rb,
lib/resources/workers.rb,
lib/resources/webhooks.rb,
lib/errors/service_error.rb,
lib/resources/containers.rb,
lib/resources/recipients.rb,
lib/resources/destinations.rb,
lib/errors/permission_error.rb,
lib/errors/rate_limit_error.rb,
lib/errors/validation_error.rb,
lib/resources/organizations.rb,
lib/resources/administrators.rb

Defined Under Namespace

Classes: Administrators, Configuration, Containers, Destinations, HttpError, Hubs, Organizations, PermissionError, RateLimitError, Recipients, ServiceError, Tasks, Teams, ValidationError, Webhooks, Workers

Class Method Summary collapse

Class Method Details

.handle_api_error(response) ⇒ Object



51
52
53
54
55
56
57
58
59
# File 'lib/utils.rb', line 51

def self.handle_api_error(response)
  if response.status == 401 || response.status == 403
    raise PermissionError, "status: #{response.status}, message: #{response.body}"
  elsif response.status >= 400 && response.status < 500
    raise HttpError, "status: #{response.status}, message: #{response.body}"
  elsif response.status >= 500
    raise ServiceError, "status: #{response.status}, message: #{response.body}"
  end
end

.request(config, method, path, body = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/utils.rb', line 8

def self.request(config, method, path, body = nil)
  response = nil
  url = "#{config.base_url}/#{path}"

  # throttling configuration to match rate limiting enforced by the API
  request = Faraday.new do |r|
    # allow up to 20 API requests per second
    r.request :rate_limiter, interval: 0.05
    r.adapter :net_http
  end

  begin
    request.set_basic_auth(config.api_key, config.api_key)
    response = request.run_request(method, url, body, config.headers)
    handle_api_error(response)
  rescue Faraday::Response::RaiseError => e
    raise HttpError, "Received the following error when making HTTP request: #{e}"
  end
  response
end

.validate_authentication(base_url, api_key) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/utils.rb', line 29

def self.validate_authentication(base_url, api_key)
  body = nil
  headers = nil
  method = 'get'.to_sym
  success = false
  request = Faraday.new
  url = "#{base_url}/auth/test"

  begin
    request.set_basic_auth(api_key, api_key)
    response = request.run_request(method, url, body, headers)
    handle_api_error(response)

    if response.status == 200
      success = true
    end
  rescue Faraday::Response::RaiseError => e
    raise HttpError, "Received the following error when running auth test: #{e}"
  end
  success
end