# frozen_string_literal: true require 'faraday' require 'truelayer/configuration' require 'truelayer/errors' 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.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