Sha256: 8a94301e1a75640b8346ee80781615da0f65b64eac039c82f9eb0be2d484e5f5

Contents?: true

Size: 1.08 KB

Versions: 2

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_ROOT_TAG = 'Error'

        class << self
          def call(response_body, expected_root_tag)
            xml = Nokogiri.XML(response_body)

            if xml.root.nil? || ![expected_root_tag, ERROR_ROOT_TAG].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 || 'USPS could not process the request.'
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
friendly_shipping-0.2.6 lib/friendly_shipping/services/usps/parse_xml_response.rb
friendly_shipping-0.2.5 lib/friendly_shipping/services/usps/parse_xml_response.rb