Class: Incognia::Client
- Inherits:
-
Object
- Object
- Incognia::Client
- Includes:
- Singleton
- Defined in:
- lib/incognia_api/client.rb
Constant Summary collapse
- LATENCY_HEADER =
"X-Incognia-Latency".freeze
Instance Method Summary collapse
- #connection ⇒ Object
- #credentials ⇒ Object
-
#initialize ⇒ Client
constructor
TODO: (ok) http/adapter specific code (ok) raises network/authentication errors (ok) handles token refreshing ok future: handles retrying.
- #request(method, endpoint = nil, data = nil, headers = {}) ⇒ Object
- #reset! ⇒ Object
Constructor Details
#initialize ⇒ Client
TODO: (ok) http/adapter specific code (ok) raises network/authentication errors (ok) handles token refreshing ok future: handles retrying
16 17 18 19 |
# File 'lib/incognia_api/client.rb', line 16 def initialize @last_latency_ms = nil @last_latency_mutex = Mutex.new end |
Instance Method Details
#connection ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/incognia_api/client.rb', line 50 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 if Incognia.config.keep_alive = { pool_size: Incognia.config.max_connections }.compact faraday.adapter :net_http_persistent, ** else faraday.adapter Faraday.default_adapter end end end |
#credentials ⇒ Object
38 39 40 41 42 |
# File 'lib/incognia_api/client.rb', line 38 def credentials @credentials = request_credentials if @credentials.nil? || @credentials.stale? @credentials end |
#request(method, endpoint = nil, data = nil, headers = {}) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/incognia_api/client.rb', line 21 def request(method, endpoint = nil, data = nil, headers = {}) json_data = JSON.generate(data) if data request_headers = Faraday::Utils::Headers.new.update(headers) request_headers[Faraday::Request::Authorization::KEY] ||= "Bearer #{credentials.access_token}" request_headers[LATENCY_HEADER] = last_latency_ms&.to_s start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) response = connection.send(method, endpoint, json_data, request_headers.compact) store_last_latency(Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) - start) if response.success? response 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 |
#reset! ⇒ Object
44 45 46 47 48 |
# File 'lib/incognia_api/client.rb', line 44 def reset! @connection&.close @connection = nil @credentials = nil end |