Class: FriendlyShipping::Services::USPSShip::ParseRateEstimatesResponse

Inherits:
Object
  • Object
show all
Extended by:
Dry::Monads::Result::Mixin
Defined in:
lib/friendly_shipping/services/usps_ship/parse_rate_estimates_response.rb

Constant Summary collapse

CURRENCY =
Money::Currency.new('USD').freeze

Class Method Summary collapse

Class Method Details

.call(request:, response:) ⇒ Success<ApiResult<Array<Rate>>>, Failure<ApiResult<String>>

Parse a rate estimates response.

Parameters:

  • request (Request)

    the request that was used to obtain this response

  • response (Response)

    the response that USPS returned

Returns:



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/friendly_shipping/services/usps_ship/parse_rate_estimates_response.rb', line 16

def call(request:, response:)
  rates = JSON.parse(response.body)['rates'].map do |rate|
    shipping_method = SHIPPING_METHODS.detect { |sm| sm.service_code == rate['mailClass'] }
    amounts = { price: money(rate['price']) }

    # Add any additional fees to the amounts hash
    rate['fees'].each_with_object(amounts) do |fee, result|
      result[fee['name']] = money(fee['price'])
    end

    FriendlyShipping::Rate.new(
      amounts: amounts,
      shipping_method: shipping_method,
      data: {
        description: rate['description'],
        zone: rate['zone']
      }
    )
  end

  success(rates, request, response)
rescue JSON::ParserError, KeyError => e
  failure(e.message, request, response)
end