Sha256: 9acc63257cfab59eee1e9b558ecf6ff21b7b3be8175d4361b7e37caf285f4b00

Contents?: true

Size: 1.5 KB

Versions: 19

Compression:

Stored size: 1.5 KB

Contents

# frozen_string_literal: true

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

module FriendlyShipping
  class HttpClient
    include Dry::Monads::Result::Mixin

    attr_reader :error_handler

    # @param [Proc] error_handler Called to handle an error if one occurs
    def initialize(error_handler: method(:wrap_in_failure))
      @error_handler = error_handler
    end

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

      Success(convert_to_friendly_response(http_response))
    rescue ::RestClient::Exception => e
      error_handler.call(e)
    end

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

      Success(convert_to_friendly_response(http_response))
    rescue ::RestClient::Exception => e
      error_handler.call(e)
    end

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

      Success(convert_to_friendly_response(http_response))
    rescue ::RestClient::Exception => e
      error_handler.call(e)
    end

    private

    def wrap_in_failure(error)
      Failure(error)
    end

    def convert_to_friendly_response(http_response)
      FriendlyShipping::Response.new(
        status: http_response.code,
        body: http_response.body,
        headers: http_response.headers
      )
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
friendly_shipping-0.5.3 lib/friendly_shipping/http_client.rb
friendly_shipping-0.5.2 lib/friendly_shipping/http_client.rb
friendly_shipping-0.5.1 lib/friendly_shipping/http_client.rb
friendly_shipping-0.5 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.14 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.13 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.12 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.11 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.10 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.9 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.8 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.7 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.6 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.5 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.4 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.3 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.2 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.1 lib/friendly_shipping/http_client.rb
friendly_shipping-0.4.0 lib/friendly_shipping/http_client.rb