lib/zoho_hub/connection.rb in zoho_hub-0.1.0 vs lib/zoho_hub/connection.rb in zoho_hub-0.1.3

- old
+ new

@@ -1,53 +1,74 @@ # frozen_string_literal: true require 'faraday' require 'faraday_middleware' +require 'rainbow' require 'zoho_hub/response' module ZohoHub class Connection attr_accessor :debug, :access_token, :expires_in, :api_domain, :refresh_token + attr_accessor :on_refresh_cb BASE_PATH = '/crm/v2/' - def initialize(access_token:, expires_in:, api_domain:, refresh_token: nil) + def initialize(access_token:, api_domain:, expires_in: 3600, refresh_token: nil) @access_token = access_token @expires_in = expires_in @api_domain = api_domain @refresh_token ||= refresh_token # do not overwrite if it's already set end def get(path, params = {}) + log "GET #{path} with #{params}" + response = with_refresh { adapter.get(path, params) } response.body end def post(path, params = {}) + log "POST #{path} with #{params}" + response = with_refresh { adapter.post(path, params) } response.body end + def put(path, params = {}) + log "PUT #{path} with #{params}" + + response = with_refresh { adapter.put(path, params) } + response.body + end + def access_token? @access_token.present? end def refresh_token? @refresh_token.present? end + def log(text) + return unless ZohoHub.configuration.debug? + + puts Rainbow("[ZohoHub] #{text}").magenta.bright + end + private def with_refresh http_response = yield response = Response.new(http_response.body) # Try to refresh the token and try again if response.invalid_token? && refresh_token? - puts 'Refreshing outdated token...' + log "Refreshing outdated token... #{@access_token}" params = ZohoHub::Auth.refresh_token(@refresh_token) + + @on_refresh_cb.call(params) if @on_refresh_cb.present? @access_token = params[:access_token] http_response = yield end