# frozen_string_literal: true require 'faraday' require 'rainbow' require 'addressable' require 'iwoca/response' module Iwoca class Connection BASE_PATH = '/api/lending/v2.1' BASE_NOTIFICATIONS_PATH = '/api/notifications/v1' def initialize(type = 'base') @base_path = type == 'notifications' ? BASE_NOTIFICATIONS_PATH : BASE_PATH end def get(path, params = {}) log "GET #{path} with #{params}" http_response = adapter.get(PathSanitizer.sanitize(path), params) log "Response: #{http_response.body}" Response.new(http_response) end def post(path, params = {}) log "POST #{path} with #{params}" http_response = adapter.post(PathSanitizer.sanitize(path), params.to_json) log "Response: #{http_response.body}" Response.new(http_response) end def put(path, params = {}) log "PUT #{path} with #{params}" http_response = adapter.put(PathSanitizer.sanitize(path), params.to_json) log "Response: #{http_response.body}" Response.new(http_response) end private def log(text) return unless Iwoca.configuration.debug? puts Rainbow("[Iwoca] #{text}").magenta.bright end def base_url Addressable::URI.join(Iwoca.configuration.api_domain, @base_path).to_s end def adapter token = Iwoca.configuration.api_key Faraday.new(url: base_url) do |conn| conn.headers['Authorization'] = "Bearer #{token}" unless token.to_s.empty? conn.headers['Content-Type'] = 'application/json' conn.headers['User-Agent'] = "ruby-iwoca-#{VERSION}" conn.response :json, parser_options: { symbolize_names: true } conn.response :logger if Iwoca.configuration.debug? conn.adapter Faraday.default_adapter end end end end