Class: FriendlyShipping::Services::UpsJson::ParseJsonResponse

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

Constant Summary collapse

SUCCESSFUL_RESPONSE_STATUS_CODE =
'1'
UNEXPECTED_ROOT_KEY_STRING =
'Empty or unexpected root key'

Class Method Summary collapse

Class Method Details

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



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/friendly_shipping/services/ups_json/parse_json_response.rb', line 12

def call(request:, response:, expected_root_key:)
  api_error_message = response.headers.try(:[], :errordescription)
  response_body = JSON.parse(response.body)

  # UPS may return a 2xx status code on an unsuccessful request and include the error description in
  # the response headers, which we will consider a failure
  if api_error_message.present?
    wrap_failure(api_error(api_error_message), request, response)
  elsif response_body.nil? || response_body.keys.first != expected_root_key
    wrap_failure(api_error(UNEXPECTED_ROOT_KEY_STRING), request, response)
  else
    Success(response_body)
  end
rescue JSON::ParserError => e
  # when the response is not valid JSON(?!), the error description in the header is more descriptive
  return wrap_failure(api_error(api_error_message), request, response) if api_error_message

  wrap_failure(e, request, response)
end