Class: Incognia::Client

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/incognia_api/client.rb

Instance Method Summary collapse

Instance Method Details

#connectionObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/incognia_api/client.rb', line 33

def connection
  return @connection if @connection

  headers = { 'User-Agent' => "incognia-ruby/#{Incognia::VERSION} " \
                      "({#{RbConfig::CONFIG['host']}}) " \
                      "{#{RbConfig::CONFIG['arch']}} " \
                      "Ruby/#{RbConfig::CONFIG['ruby_version']}" }

  @connection = Faraday.new(Incognia.config.host, headers: headers) do |faraday|
    faraday.request :json
    faraday.response :json, content_type: /\bjson$/
    faraday.response :raise_error

    faraday.adapter Faraday.default_adapter
  end
end

#credentialsObject



27
28
29
30
31
# File 'lib/incognia_api/client.rb', line 27

def credentials
  @credentials = request_credentials if @credentials.nil? || @credentials.stale?

  @credentials
end

#request(method, endpoint = nil, data = nil, headers = {}) ⇒ Object

TODO: (ok) http/adapter specific code (ok) raises network/authentication errors (ok) handles token refreshing ok future: handles retrying



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/incognia_api/client.rb', line 13

def request(method, endpoint = nil, data = nil, headers = {})
  json_data = JSON.generate(data) if data

  connection.send(method, endpoint, json_data, headers) do |r|
    r.headers[Faraday::Request::Authorization::KEY] ||= Faraday::Request
      .lookup_middleware(:authorization)
      .header(:Bearer, credentials.access_token)
  end
rescue Faraday::ClientError, Faraday::ServerError => e
  raise APIError.new(e.to_s, e.response)
rescue Faraday::Error => e
  raise APIError.new(e.to_s)
end