Sha256: 404c6b748610e3bff505f5af8cf4772e20a8469746498bce664db50149ba3531

Contents?: true

Size: 1.52 KB

Versions: 3

Compression:

Stored size: 1.52 KB

Contents

# frozen_string_literal: true

require 'faraday'
require '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
      username = Creditsafe.configuration.username
      passwd = Creditsafe.configuration.password

      @connection ||= Faraday.new(url: api_url) do |conn|
        conn.request :creditsafe_auth, username, passwd
        conn.response :json, parser_options: { symbolize_names: true }
        conn.response :logger if Creditsafe.configuration.debug
        conn.adapter Faraday.default_adapter
      end
    end

    def api_url
      BASE_URLS[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.7 lib/creditsafe/client.rb
creditsafe_connect-0.1.6 lib/creditsafe/client.rb
creditsafe_connect-0.1.5 lib/creditsafe/client.rb