Class: FriendlyShipping::Services::ShipEngine::ParseRateEstimateResponse

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

Class Method Summary collapse

Class Method Details

.call(response:, request:, options:) ⇒ Object



12
13
14
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
# File 'lib/friendly_shipping/services/ship_engine/parse_rate_estimate_response.rb', line 12

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,
      service_code: rate['service_code']
    )

    amounts = get_amounts(rate)
    FriendlyShipping::Rate.new(
      shipping_method: shipping_method,
      amounts: amounts,
      remote_service_id: rate['rate_id'],
      delivery_date: Time.parse(rate['estimated_delivery_date']),
      warnings: rate['warning_messages'],
      errors: rate['error_messages']
    )
  end.compact

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