Sha256: 6eda5a5934eb5a54db6791337f5f602ad3911523d03078f110b93446a6415571

Contents?: true

Size: 1.08 KB

Versions: 3

Compression:

Stored size: 1.08 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(response_body, expected_root_tag)
            xml = Nokogiri.XML(response_body)

            if xml.root.nil? || ![expected_root_tag, 'Error'].include?(xml.root.name)
              Failure('Invalid document')
            elsif request_successful?(xml)
              Success(xml)
            else
              Failure(error_message(xml))
            end
          rescue Nokogiri::XML::SyntaxError => e
            Failure(e)
          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
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
friendly_shipping-0.3.4 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.3.3 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.3.0 lib/friendly_shipping/services/usps/parse_xml_response.rb