Sha256: 2c1df5f0e129705f3b6fc2caa42c6620dbec98b4ba620743c20be0c1807e72a2

Contents?: true

Size: 1.43 KB

Versions: 6

Compression:

Stored size: 1.43 KB

Contents

# frozen_string_literal: true

require 'dry/monads'
require 'rest-client'

require 'friendly_shipping/api_failure'
require 'friendly_shipping/api_error_handler'

module FriendlyShipping
  class HttpClient
    include Dry::Monads[:result]

    attr_reader :error_handler

    # @param [Proc] error_handler Called to handle an error if one occurs
    def initialize(error_handler: FriendlyShipping::ApiErrorHandler.new)
      @error_handler = error_handler
    end

    def get(request)
      http_response = ::RestClient.get(
        request.url, request.headers
      )

      Success(Response.new_from_rest_client_response(http_response))
    rescue ::RestClient::Exception => e
      error_handler.call(e, original_request: request, original_response: e.response)
    end

    def post(request)
      http_response = ::RestClient.post(
        request.url,
        request.body,
        request.headers
      )

      Success(Response.new_from_rest_client_response(http_response))
    rescue ::RestClient::Exception => e
      error_handler.call(e, original_request: request, original_response: e.response)
    end

    def put(request)
      http_response = ::RestClient.put(
        request.url,
        request.body,
        request.headers
      )

      Success(Response.new_from_rest_client_response(http_response))
    rescue ::RestClient::Exception => e
      error_handler.call(e, original_request: request, original_response: e.response)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
friendly_shipping-0.8.1 lib/friendly_shipping/http_client.rb
friendly_shipping-0.8.0 lib/friendly_shipping/http_client.rb
friendly_shipping-0.7.3 lib/friendly_shipping/http_client.rb
friendly_shipping-0.7.2 lib/friendly_shipping/http_client.rb
friendly_shipping-0.7.1 lib/friendly_shipping/http_client.rb
friendly_shipping-0.7.0 lib/friendly_shipping/http_client.rb