Module: OldSchool::API::Utils

Included in:
OldSchool::API
Defined in:
lib/old_school/api/utils.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#idObject

Returns the value of attribute id.



12
13
14
# File 'lib/old_school/api/utils.rb', line 12

def id
  @id
end

#secretObject

Returns the value of attribute secret.



12
13
14
# File 'lib/old_school/api/utils.rb', line 12

def secret
  @secret
end

#url_factoryObject

Returns the value of attribute url_factory.



12
13
14
# File 'lib/old_school/api/utils.rb', line 12

def url_factory
  @url_factory
end

Instance Method Details

#as_array(item) ⇒ Object



171
172
173
174
175
# File 'lib/old_school/api/utils.rb', line 171

def as_array(item)
  return item.clone if item.is_a?(Array)
  return [] if item.nil?
  return [item]
end

#collection_from_response(response, keys = nil) ⇒ Object



34
35
36
# File 'lib/old_school/api/utils.rb', line 34

def collection_from_response(response, keys = nil)
  as_array hash_from_response!(response, keys) { [] }
end

#default_headersObject



107
108
109
110
111
112
113
# File 'lib/old_school/api/utils.rb', line 107

def default_headers
  {
    Authorization: "Bearer #{token}",
    Accept: 'application/JSON',
    'Content-Type'=>'application/JSON'
  }
end

#delete(uri) ⇒ Object



137
138
139
140
141
142
# File 'lib/old_school/api/utils.rb', line 137

def delete(uri)
  Typhoeus.delete(
    make_sane_uri(uri),
    headers: default_headers
  )
end

#extract_from_response_options(response, key) ⇒ Object



99
100
101
102
103
104
105
# File 'lib/old_school/api/utils.rb', line 99

def extract_from_response_options(response, key)
  begin
    return response.options[key]
  rescue
    return nil
  end
end

#get(uri) ⇒ Object



115
116
117
118
119
120
# File 'lib/old_school/api/utils.rb', line 115

def get(uri)
  Typhoeus.get(
    make_sane_uri(uri),
    headers: default_headers
  )
end

#get_many(items, keys, uri_proc, complete_proc = nil) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/old_school/api/utils.rb', line 177

def get_many(items, keys, uri_proc, complete_proc = nil)
  hydra = Typhoeus::Hydra.hydra
  requests = []
  items.each do |item|
    uri = uri_proc.call(item)
    request = get_wait(uri)
    request.on_complete {|response| complete_proc.call(response)} unless complete_proc.nil?
    requests << [item, request]
    hydra.queue request
  end

  hydra.run

  responses = {}
  requests.each do |request|
    responses[request[0]] = hash_from_response(request[1].response, keys)
  end
  responses
end

#get_wait(uri) ⇒ Object



122
123
124
125
126
127
# File 'lib/old_school/api/utils.rb', line 122

def get_wait(uri)
  Typhoeus::Request.new(
    make_sane_uri(uri),
    method: :get,
    headers: default_headers)
end

#get_with_pagination_url(resource, num_items, &uri_proc) ⇒ Object



160
161
162
163
164
165
166
167
168
169
# File 'lib/old_school/api/utils.rb', line 160

def get_with_pagination_url(resource, num_items, &uri_proc)
  return [] if num_items == 0 #if paginating for zero items, just return an empty list

  #calculate page size based on
  page_size = ["#{resource}_max_page_size"]
  pages = (num_items - 1) / page_size + 1

  results = get_many((1..pages), ["#{resource}s", resource], uri_proc)
  results.values.flatten
end

#hash_from_response(response, keys = nil) ⇒ Object



38
39
40
41
42
# File 'lib/old_school/api/utils.rb', line 38

def hash_from_response(response, keys = nil)
  hash_from_response!(response, keys) do |body, key|
    raise ResponseError, "\"#{key}\" key not in response object:\n #{response.body}:\nfrom original:\n#{response.inspect.to_s}" unless body.has_key?(key)
  end
end

#hash_from_response!(response, keys) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/old_school/api/utils.rb', line 44

def hash_from_response!(response, keys)
  keys = as_array keys
  validate_response response
  body = parse_json response

  while keys.size > 0
    key = keys.shift
    if body.has_key?(key)
      body = body[key]
    else
      return yield(body, key) if block_given?
      return nil
    end
  end

  body
end

#hash_without_nil_values(hash) ⇒ Object



62
63
64
# File 'lib/old_school/api/utils.rb', line 62

def hash_without_nil_values(hash)
  hash.to_hash.delete_if{ |k,v| v.nil? }
end

#make_sane_uri(uri) ⇒ Object



152
153
154
155
156
157
158
# File 'lib/old_school/api/utils.rb', line 152

def make_sane_uri(uri)
  if /\Ahttps?/.match(uri)
    uri
  else
    @url_factory.merge_with_base(uri)
  end
end

#parse_error(response) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
# File 'lib/old_school/api/utils.rb', line 74

def parse_error(response)
  error = parse_json(response)["errorMessage"]
  begin
    msg = "#{error["message"]} ("
    msg += "#{error["errors"]["resource"]}#{error["errors"]["field"] ? "." : ""}#{error["errors"]["field"]}"
    msg +=": #{error["errors"]["code"]})"
    return [error["errors"]["code"], msg]
  rescue
    return ["ERROR", response.body]
  end
end

#parse_json(response) ⇒ Object



66
67
68
69
70
71
72
# File 'lib/old_school/api/utils.rb', line 66

def parse_json(response)
  begin
    body = JSON.parse(response.body)
  rescue JSON::ParserError
    raise ResponseError, "Could not parse body as JSON: #{response.body}"
  end
end

#post(uri, body) ⇒ Object



144
145
146
147
148
149
150
# File 'lib/old_school/api/utils.rb', line 144

def post(uri, body)
  Typhoeus.post(
    make_sane_uri(uri),
    headers: default_headers,
    body: body
  )
end

#put(uri, body) ⇒ Object



129
130
131
132
133
134
135
# File 'lib/old_school/api/utils.rb', line 129

def put(uri, body)
  Typhoeus.put(
    make_sane_uri(uri),
    headers: default_headers,
    body: body
  )
end

#resource_metadataObject



14
15
16
# File 'lib/old_school/api/utils.rb', line 14

def 
  @resource_metadata ||= hash_from_response(get(@url_factory.),'metadata')
end

#tokenObject



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/old_school/api/utils.rb', line 18

def token
  return @token unless @token.nil?
  response = Typhoeus.post(
    @url_factory.access_token_url,
    userpwd: "#{@id}:#{@secret}",
    params: {
      grant_type: 'client_credentials'
    })

  @token = hash_from_response(response, 'access_token')
end

#token=(token) ⇒ Object



30
31
32
# File 'lib/old_school/api/utils.rb', line 30

def token=(token)
  @token = token
end

#validate_response(response) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/old_school/api/utils.rb', line 86

def validate_response(response)
  if response.success?
    return
  elsif response.timed_out?
    raise ResponseError, 'HTTP request timed out'
  elsif response.code == 0
    raise ResponseError, response.return_message
  else
    reason = extract_from_response_options(response, :response_headers)
    raise ResponseError, "HTTP request failed: #{response.code}:\n#{reason}"
  end
end