Sha256: a8a67dfbbe953d3d5c5246c79588526aa6e9f6ac6013152ffa6d163548c12bb2

Contents?: true

Size: 1.48 KB

Versions: 3

Compression:

Stored size: 1.48 KB

Contents

# frozen_string_literal: true

require 'faraday'
require 'faraday_middleware/multi_json'
require 'creditsafe/configuration'
require 'creditsafe/faraday_auth'

module Creditsafe
  class Client
    BASE_URLS = {
      production: 'https://connect.creditsafe.com/v1/',
      sandbox: 'https://connect.sandbox.creditsafe.com/v1/'
    }.freeze

    def initialize
      Faraday::Request.register_middleware creditsafe_auth: -> { Creditsafe::FaradayAuth }
    end

    def get(path, params = {})
      connection.get(path, params).tap do |response|
        handle_response(response)
      end
    end

    def post(path, params = {})
      connection.post(path, MultiJson.dump(params)).tap do |response|
        handle_response(response)
      end
    end

    def connection
      @connection ||= Faraday.new(url: api_url) do |conn|
        conn.request :creditsafe_auth, Creditsafe.configuration.username, Creditsafe.configuration.password
        conn.response :multi_json, symbolize_keys: true
        conn.response :logger if Creditsafe.configuration.debug
        conn.adapter Faraday.default_adapter
      end
    end

    def api_url
      BASE_URLS.dig(Creditsafe.configuration.environment.to_sym)
    end

    def handle_response(response)
      return if response.success?

      case response.status
      when 401
        raise UnauthorizedError, response.body
      when 400
        raise InvalidRequestError, response.body
      else
        raise GenericError, response.body
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
creditsafe_connect-0.1.2 lib/creditsafe/client.rb
creditsafe_connect-0.1.1 lib/creditsafe/client.rb
creditsafe_connect-0.1.0 lib/creditsafe/client.rb