Sha256: 6b02beb36d4ca84c3fc46bb39965230cdd8fccc8dd3b80bf06b8c570b6bf8514

Contents?: true

Size: 1.88 KB

Versions: 1

Compression:

Stored size: 1.88 KB

Contents

# frozen_string_literal: true

require 'faraday'
require 'faraday_middleware/multi_json'
require 'credit_gateway/configuration'
require 'credit_gateway/faraday_auth'
require 'credit_gateway/errors'

module CreditGateway
  class Client
    def initialize
      return if Faraday::Request.fetch_middleware(:credit_gateway_auth)

      Faraday::Request.register_middleware credit_gateway_auth: -> { CreditGateway::FaradayAuth }
    end

    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, MultiJson.dump(params), headers).tap do |response|
        handle_response(response)
      end
    end

    def connection
      @connection ||= Faraday.new(url: api_url) do |conn|
        conn.request :credit_gateway_auth,
                     CreditGateway.configuration.client_id,
                     CreditGateway.configuration.client_secret
        conn.response :multi_json, symbolize_keys: 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
        if response.body.dig(:Errors, 0, :ErrorCode) == 'Company.NotFound'
          raise CompanyNotFoundError, response.body.dig(:Errors, 0, :ErrorMessage)
        else
          raise InvalidRequestError, response.body
        end
      when 401
        raise UnauthorizedError, response.body
      when 404
        raise NotFoundError, response.body
      else
        raise GenericError, "#{response.status}: #{response.body}"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
credit_gateway-0.1.1 lib/credit_gateway/client.rb