# frozen_string_literal: true module ErpIntegration module Fulfil module Persistence # Allows creating new resources in Fulfil. # # @param attributes [Hash] A list of attributes for the new resource. # @return [Array|Hash] The response from the API def create(attributes) client .post("model/#{model_name}", normalize_attributes(attributes)) .map { |new_record_id| attributes.merge!(id: new_record_id) } .first rescue ErpIntegration::HttpError::BadRequest => e [attributes, [extract_error_message(e)]] end # Updates the resource with the given attributes. # # @param resource_id [Integer] The ID of the resource. # @param attributes [Hash] A list of attributes to update for the resource. # @return [Array|Hash] The response from the API def update(resource_id, attributes) client.put("model/#{model_name}/#{resource_id}", attributes) rescue ErpIntegration::HttpError::BadRequest => e [attributes, [extract_error_message(e)]] end # Destroys the resource. # # @param resource_id [Integer] The ID of the resource. # @return [Boolean] Returns true if the resource was deleted def destroy(resource_id) client.delete("model/#{model_name}/#{resource_id}") { id: resource_id } rescue ErpIntegration::HttpError::BadRequest => e [{ id: resource_id }, [extract_error_message(e)]] 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] The attributes for the new resource. # @return [Array] The normalized attributes. def normalize_attributes(attributes) attrs = attributes.is_a?(Array) ? attributes : [attributes] attrs.compact end end end end