# frozen_string_literal: true require 'faraday' require 'credit_gateway/configuration' require 'credit_gateway/faraday_auth' require 'credit_gateway/errors' module CreditGateway class Client def get(path, headers: {}, params: {}) connection.get(path, params, headers).tap do |response| handle_response(response) end end def post(path, headers: {}, params: {}) connection.post(path, JSON.generate(params), headers).tap do |response| handle_response(response) end end def connection @connection ||= Faraday.new(url: api_url) do |conn| conn.use CreditGateway::FaradayAuth, CreditGateway.configuration.client_id, CreditGateway.configuration.client_secret, CreditGateway.configuration.country conn.response :json, parser_options: { symbolize_names: true } if CreditGateway.configuration.debug conn.response :logger, nil, { headers: true, bodies: CreditGateway.configuration.verbose } end conn.adapter Faraday.default_adapter end end def api_url CreditGateway.configuration.base_url end def handle_response(response) return if response.success? case response.status when 400 handle_company_not_found(response.body, InvalidRequestError) when 401 raise UnauthorizedError, response.body when 404 handle_company_not_found(response.body, NotFoundError) when 409 raise ConflictError, response.body else raise GenericError, "#{response.status}: #{response.body}" end end def handle_company_not_found(body, alternative_exception) raise CompanyNotFoundError, body.dig(0, :message) if body.dig(0, :code) == 'company_not_found' raise alternative_exception, body end end end