Sha256: 6e93494eb5f17ef3593f500381899d3749ecbc956baf7221830782e2a9cb0b07

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

# frozen_string_literal: true

require 'json'
require 'friendly_shipping/services/rl/shipment_document'

module FriendlyShipping
  module Services
    class RL
      # Parses the response from the R+L API when printing shipping labels.
      class ParsePrintShippingLabelsResponse
        extend Dry::Monads::Result::Mixin

        class << self
          # @param request [Request] the request to attach to the API result
          # @param response [Response] the response to parse
          # @return [Result<ApiResult<ShipmentDocument>>] shipping document containing the labels
          def call(request:, response:)
            parsed_json = JSON.parse(response.body)
            label_doc = ShipmentDocument.new(
              format: :pdf,
              document_type: :label,
              binary: Base64.decode64(parsed_json['ShippingLabelsFile'])
            )
            if label_doc.valid?
              Success(
                ApiResult.new(
                  label_doc,
                  original_request: request,
                  original_response: response
                )
              )
            else
              errors = parsed_json.fetch('Errors', [{ 'ErrorMessage' => 'Unknown error' }])
              Failure(
                ApiResult.new(
                  errors.map { |e| e['ErrorMessage'] },
                  original_request: request,
                  original_response: response
                )
              )
            end
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
friendly_shipping-0.9.0 lib/friendly_shipping/services/rl/parse_print_shipping_labels_response.rb