Sha256: 06be74ff1b4efb82e879dd5745c5e082d147f84cde43eb201893849d1a595835

Contents?: true

Size: 1.45 KB

Versions: 14

Compression:

Stored size: 1.45 KB

Contents

# frozen_string_literal: true

module FriendlyShipping
  module Services
    class Usps
      class ParseXMLResponse
        extend Dry::Monads::Result::Mixin
        ERROR_TAG = 'Error'

        class << self
          def call(request:, response:, expected_root_tag:)
            xml = Nokogiri.XML(response.body, &:strict)

            if xml.root.nil? || ![expected_root_tag, 'Error'].include?(xml.root.name)
              wrap_failure('Invalid document', request, response)
            elsif request_successful?(xml)
              Success(xml)
            else
              wrap_failure(error_message(xml), request, response)
            end
          rescue Nokogiri::XML::SyntaxError => e
            wrap_failure(e, request, response)
          end

          private

          def request_successful?(xml)
            xml.xpath('//Error/Number')&.text.blank?
          end

          def error_message(xml)
            number = xml.xpath('//Error/Number')&.text
            desc = xml.xpath('//Error/Description')&.text
            [number, desc].select(&:present?).join(': ').presence&.strip || 'USPS could not process the request.'
          end

          def wrap_failure(failure, request, response)
            Failure(
              FriendlyShipping::ApiFailure.new(
                failure,
                original_request: request,
                original_response: response
              )
            )
          end
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
friendly_shipping-0.9.0 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.8.1 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.8.0 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.7.3 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.7.2 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.7.1 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.7.0 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.6.5 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.6.4 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.6.3 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.6.2 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.6.1 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.6.0 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.5.3 lib/friendly_shipping/services/usps/parse_xml_response.rb