Class: FriendlyShipping::Services::ShipEngine::ParseRateEstimatesResponse

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

Overview

Parses the rate estimates API response.

Class Method Summary collapse

Class Method Details

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

Returns the parsed rate estimates or errors.

Parameters:

  • request (Request)

    the request to attach to the API result

  • response (Response)

    the response to parse

  • options (RateEstimatesOptions)

    the options to use when parsing

Returns:

  • (Success<ApiResult<Array<Rate>>>, Failure<ApiResult<Array<String>>>)

    the parsed rate estimates or errors



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/friendly_shipping/services/ship_engine/parse_rate_estimates_response.rb', line 15

def call(response:, request:, options:)
  error_messages = []
  parsed_json = JSON.parse(response.body)
  rates = parsed_json.map do |rate|
    if rate['validation_status'] == 'invalid'
      error_messages.concat rate['error_messages']
      next
    end

    carrier = options.carriers.detect { |c| c.id == rate['carrier_id'] }
    next unless carrier

    shipping_method = FriendlyShipping::ShippingMethod.new(
      carrier: carrier,
      name: rate['service_type'],
      service_code: rate['service_code']
    )

    amounts = get_amounts(rate)
    FriendlyShipping::Rate.new(
      shipping_method: shipping_method,
      amounts: amounts,
      remote_service_id: rate['rate_id'],
      pickup_date: rate['ship_date'] && Time.parse(rate['ship_date']),
      delivery_date: rate['estimated_delivery_date'] && Time.parse(rate['estimated_delivery_date']),
      guaranteed: rate['guaranteed_service'],
      warnings: rate['warning_messages'],
      errors: rate['error_messages'],
      data: {
        package_type: rate['package_type'],
        delivery_days: rate['delivery_days'],
        carrier_delivery_days: rate['carrier_delivery_days'],
        negotiated_rate: rate['negotiated_rate'],
        trackable: rate['trackable'],
        validation_status: rate['validation_status']
      }
    )
  end.compact

  if valid_rates(parsed_json)
    Success(
      ApiResult.new(
        rates,
        original_request: request,
        original_response: response
      )
    )
  else
    Failure(
      ApiResult.new(
        error_messages,
        original_request: request,
        original_response: response
      )
    )
  end
end