class CapitalOnTap::Connection

Constants

BASE_PATH

Attributes

access_token[RW]
debug[RW]
expires_in[RW]
on_refresh_cb[RW]

This is a block to be run when the token is refreshed. This way you can do whatever you want with the new parameters returned by the refresh method.

refresh_token[RW]

Public Class Methods

new(access_token:, expires_in: 1200, refresh_token: nil) click to toggle source
# File lib/capital_on_tap/connection.rb, line 20
def initialize(access_token:, expires_in: 1200, refresh_token: nil)
  @access_token = access_token
  @expires_in = expires_in
  @refresh_token ||= refresh_token # do not overwrite if it's already set
end

Public Instance Methods

get(path, params = {}) click to toggle source
# File lib/capital_on_tap/connection.rb, line 26
def get(path, params = {})
  log "GET #{path} with #{params}"

  http_response = with_refresh { adapter.get(path, params) }

  log "Response: #{http_response.body}"

  Response.new(http_response)
end
log(text) click to toggle source
# File lib/capital_on_tap/connection.rb, line 46
def log(text)
  return unless CapitalOnTap.configuration.debug?

  puts Rainbow("[CapitalOnTap] #{text}").magenta.bright
end
post(path, params = {}) click to toggle source
# File lib/capital_on_tap/connection.rb, line 36
def post(path, params = {})
  log "POST #{path} with #{params}"

  http_response = with_refresh { adapter.post(path, params.to_json) }

  log "Response: #{http_response.body}"

  Response.new(http_response)
end

Private Instance Methods

adapter() click to toggle source
# File lib/capital_on_tap/connection.rb, line 81
def adapter
  Faraday.new(url: base_url) do |conn|
    conn.headers['Authorization'] = "Bearer #{@access_token}" unless @access_token.to_s.empty?
    conn.headers['Content-Type'] = 'application/json'
    conn.use FaradayMiddleware::ParseJson
    conn.response :json, parser_options: { symbolize_names: true }
    # conn.response :logger if CapitalOnTap.configuration.debug?
    conn.adapter Faraday.default_adapter
  end
end
authorization_header() click to toggle source

The authorization header that must be added to every request for authorized requests.

# File lib/capital_on_tap/connection.rb, line 77
def authorization_header
  { 'Authorization' => "Bearer #{@access_token}" }
end
base_url() click to toggle source
# File lib/capital_on_tap/connection.rb, line 72
def base_url
  Addressable::URI.join(CapitalOnTap.configuration.base_url, BASE_PATH).to_s
end
with_refresh(&block) click to toggle source
# File lib/capital_on_tap/connection.rb, line 54
def with_refresh(&block)
  http_response = block.call

  response = Response.new(http_response)

  # Get a new access token if needed
  if !response.success? && response.invalid_token?
    params = CapitalOnTap::Auth.refresh_access_token(@refresh_token)

    @access_token = params[:access_token]
    @refresh_token = params[:refresh_token]

    http_response = block.call
  end

  http_response
end