Sha256: 72b606ca970c20ae4c227291d3a20762eb95cf47352b230d0ce28b1e6364177d

Contents?: true

Size: 1.63 KB

Versions: 1

Compression:

Stored size: 1.63 KB

Contents

# frozen_string_literal: true

require 'faraday'

require 'truelayer/configuration'
require 'truelayer/errors'
require 'truelayer/faraday_auth'

module Truelayer
  class Client
    def initialize(access_token)
      @access_token = access_token
    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, params, headers).tap do |response|
        handle_response(response)
      end
    end

    private

    attr_reader :access_token

    def base_url
      Truelayer.configuration.base_url
    end

    def connection
      @connection ||= Faraday.new(url: base_url) do |conn|
        # conn.request :truelayer_auth, access_token
        conn.use Truelayer::FaradayAuth, access_token
        conn.response :json, parser_options: { symbolize_names: true }
        if Truelayer.configuration.debug
          conn.response :logger, nil, { headers: true, bodies: Truelayer.configuration.verbose }
        end
        conn.adapter Faraday.default_adapter
      end
    end

    def handle_response(response)
      return if response.success?

      case response.status
      when 400
        raise InvalidRequestError, response.body
      when 401
        raise UnauthorizedError, response.body
      when 403
        raise AccessDeniedError, response.body
      when 404
        raise NotFoundError, response.body
      when 501
        raise EndpointNotSupportedError, 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
truelayer-0.1.4 lib/truelayer/client.rb