Class: LL::WK::API::Connection::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/ll/wk/api/connection/base.rb

Direct Known Subclasses

Curb, HTTParty

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, email:, password:) ⇒ Base

Returns a new instance of Base.



34
35
36
37
38
39
# File 'lib/ll/wk/api/connection/base.rb', line 34

def initialize(url:, email:, password:)
  LL::WK::API.logger.debug("API Connection initialize(url: #{url}, email: #{email}, password: xxxx)")
  @url = url
  @email = email
  @password = password
end

Instance Attribute Details

#emailObject (readonly)

Returns the value of attribute email.



6
7
8
# File 'lib/ll/wk/api/connection/base.rb', line 6

def email
  @email
end

#passwordObject (readonly)

Returns the value of attribute password.



6
7
8
# File 'lib/ll/wk/api/connection/base.rb', line 6

def password
  @password
end

#tokenObject (readonly)

Returns the value of attribute token.



6
7
8
# File 'lib/ll/wk/api/connection/base.rb', line 6

def token
  @token
end

#token_issuedObject (readonly)

Returns the value of attribute token_issued.



6
7
8
# File 'lib/ll/wk/api/connection/base.rb', line 6

def token_issued
  @token_issued
end

#urlObject (readonly)

Returns the value of attribute url.



6
7
8
# File 'lib/ll/wk/api/connection/base.rb', line 6

def url
  @url
end

Class Method Details

.authenticate_payload(email, password) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/ll/wk/api/connection/base.rb', line 8

def self.authenticate_payload(email, password)
  {
    user: {
      email: email,
      password: password
    }
  }.to_json
end

.trap_resp_code(code, klass = LL::WK::API::Connection::Error) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/ll/wk/api/connection/base.rb', line 17

def self.trap_resp_code(code, klass = LL::WK::API::Connection::Error)
  case code
  when 403
    LL::WK::API.logger.debug('API Unautorized')
    raise LL::WK::API::Connection::AuthenticationError, 'Unauthorized'
  when 404
    LL::WK::API.logger.debug('API invalid endpoint')
    raise klass, 'Invalid endpoint'
  when 400..499
    LL::WK::API.logger.debug("API Client Error: #{code}")
    raise klass, 'Client error #{code}'
  when 500..599
    LL::WK::API.logger.debug("API Server Error: #{code}")
    raise klass, "Server Error #{code}"
  end
end

Instance Method Details

#authObject



41
42
43
# File 'lib/ll/wk/api/connection/base.rb', line 41

def auth
  "Token token=\"#{@token}\", email=\"#{@email}\""
end

#authenticate!(force = false) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/ll/wk/api/connection/base.rb', line 45

def authenticate!(force = false)
  LL::WK::API.logger.debug("API authenitcate!(#{force})")
  return self unless token_expired? or force

  retries = 0
  begin
    self.class.authenticate(email, password, url) do |resp|
      self.class.trap_resp_code(resp.code, LL::WK::API::Connection::AuthenticationError)
      @token = resp.parsed_response['token']
      @token_issued = Time.now
    end
  rescue LL::WK::API::Connection::AuthenticationError => e
    retries += 1
    sleep retries
    retry if retries < 2
    raise e
  end
  self
end

#from_api(endpoint, params, &block) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/ll/wk/api/connection/base.rb', line 65

def from_api(endpoint, params, &block)
  # with_page modifies the context, so need to clone it otherwise you 
  # get unexpected behaviour from the calling context
  p = params.clone
  LL::WK::API.logger.debug("API from_api ep: #{endpoint} params: #{params}")
  retries = 0
  return with_cursor(endpoint, p, &block) if LL::WK::API::Connection::SUPPORTS_CURSOR
  with_page(endpoint, p, &block)
rescue AuthenticationError => e
  authenticate!
  retries += 1
  retry if retries < 3
  raise e
end

#page_count(resp) ⇒ Object



80
81
82
# File 'lib/ll/wk/api/connection/base.rb', line 80

def page_count(resp)
  resp['paging']&.[]('total')
end

#retrieve_data(endpoint, params, &block) ⇒ Object



125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/ll/wk/api/connection/base.rb', line 125

def retrieve_data(endpoint, params, &block)
  retries = 0
  LL::WK::API.benchmark("http call #{endpoint}") do
    response_from_api(endpoint, params, &block)
  end
rescue LL::WK::API::Connection::Error => e
  authenticate!(true)
  retries += 1
  sleep 1
  retry if retries < 3
  raise e
end

#token_expired?Boolean

Returns:

  • (Boolean)


84
85
86
87
# File 'lib/ll/wk/api/connection/base.rb', line 84

def token_expired?
  return true unless token
  true unless (Time.now - token_issued.to_i).to_i < 76400
end

#with_cursor(endpoint, params) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/ll/wk/api/connection/base.rb', line 89

def with_cursor(endpoint, params)
  LL::WK::API.logger.debug("API call uses cursors")
  params[:cursor] ||= 0
  array = []
  while !params[:cursor].nil?
    retrieve_data(endpoint, params) do |resp|
      resp['data'].each do |item|
        array << item
        yield(item) if block_given?
      end
      params[:cursor] = resp[:cursor]
    end
  end
  array
end

#with_page(endpoint, params) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/ll/wk/api/connection/base.rb', line 105

def with_page(endpoint, params)
  LL::WK::API.logger.debug("API call uses pagination")
  params[:page] ||= 1
  pages_remain = params[:page] + 1
  array = []
  while params[:page] < pages_remain
    retrieve_data(endpoint, params) do |resp|
      resp['data'].each do |item|
        array << item
        yield(item) if block_given?
      end
      pages_remain = page_count(resp)
      LL::WK::API.logger.debug("finished with page #{params[:page]} of #{pages_remain}")
      params[:page] += 1
    end
  end
  LL::WK::API.logger.debug "found or worked on #{array.size} items"
  array
end