Class: ActionNetworkRest::Base

Inherits:
Vertebrae::Model
  • Object
show all
Defined in:
lib/action_network_rest/base.rb

Instance Method Summary collapse

Instance Method Details

#allObject



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
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/action_network_rest/base.rb', line 20

def all
  min_wait = 0.25 # sec to wait between calls
  timestamp = Time.now.to_r # secs since Unix Epoch
  page_number = 1
  tries = 0
  all = []
  loop do
    # Limit rate before request to avoid error
    wait = min_wait * (1.5**tries)
    new_time = Time.now.to_r
    if (timestamp + min_wait - new_time).positive?
      sleep(wait) # Wait if calling again could exceed the rate limit
      tries += 1
      next # check again
    end

    begin
      page = list(page: page_number)
    rescue ActionNetworkRest::Response::TooManyRequests
      if tries >= 10
        raise ActionNetworkRest::Response::UsedAllRequestTries,
              {
                tries: tries,
                last_wait_length: wait,
                resource: base_path
              }.to_json
      end

      sleep(wait)
      tries += 1 # Exponential back off if got Too Many Requests error response
      next
    end
    timestamp = Time.now.to_r

    break if page.empty?

    all.concat(page)
    page_number += 1
    tries = 0
  end
  all
end

#get(id) ⇒ Object



5
6
7
8
# File 'lib/action_network_rest/base.rb', line 5

def get(id)
  response = client.get_request "#{base_path}#{url_escape(id)}"
  object_from_response(response)
end

#list(page: 1) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'lib/action_network_rest/base.rb', line 10

def list(page: 1)
  response = client.get_request "#{base_path}?page=#{url_escape(page)}"
  objects = response.body.dig('_embedded', osdi_key)
  return [] if objects.nil?

  objects.each { |obj| set_action_network_id_on_object(obj) }

  objects
end