Sha256: 2d6948baf3ddb1d3746478a08e1a5e74ed78bd50e2709399bf237f41732f542e

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 KB

Contents

# frozen_string_literal: true

module ErpIntegration
  module Fulfil
    module Persistence
      # Allows creating new resources in Fulfil.
      #
      # @example
      #   $ ErpIntegration::Product.create(code: 'MT100eu', variant: 10)
      #   => <ErpIntegration::Product @id=2 @code="MT100eu" @variant=10 />
      #
      # @param attributes [Hash] A list of attributes.
      # @return [ErpIntegration::Resource] The newly created resource.
      def create(attributes = {})
        client
          .post("model/#{model_name}", normalize_attributes(attributes))
          .map { |new_record_id| resource_klass.new(attributes.merge(id: new_record_id)) }
          .first
      rescue ErpIntegration::HttpError::BadRequest => e
        record = resource_klass.new(attributes)
        record.errors.add(extract_error_message(e))
        record
      end

      private

      # Fulfil returns a 400 status code (e.g. Bad Request) with the error message
      # in the body. We're using the exception to extract the error message in the
      # body of the original response from Fulfil.
      #
      # @param error [ErpIntegration::HttpError::BadRequest] The exception raised by our middleware.
      # @return [String] The error message by Fulfil.
      def extract_error_message(error)
        JSON.parse(error.response[:body]).fetch('message')
      end

      # Fulfil always expects an array of attributes. That way, we could also create
      # a whole bunch of objects all at once. We don't support creating multiple records
      # yet as it's not needed yet. However, we do need to normalize the attributes we're
      # passing to the Fulfil API.
      #
      # @param attributes [Hash|Array<Hash>] The attributes for the new resource.
      # @return [Array<Hash>] The normalized attributes.
      def normalize_attributes(attributes)
        attrs = attributes.is_a?(Array) ? attributes : [attributes]
        attrs.compact
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
erp_integration-0.7.0 lib/erp_integration/fulfil/persistence.rb