module Alula module ApiOperations module Save def self.extended(base) base.include(InstanceMethods) end module InstanceMethods def save payload = { data: { id: id, attributes: as_patchable_json } } payload[:data].delete(:id) if video_request?(resource_url) response = Alula::Client.request(:patch, resource_url, payload, {}) if response.ok? construct_from(response.data['data']) return true end handle_errors(response) end def save! save || raise(ValidationError.new(self.errors)) end def create data = { attributes: as_patchable_json } # # Most creations _won't_ have an ID, but the Alula API utlizes a shared GUID strategy for a few resources # We need to conditionally include this ID in the data array even though the record 'doesnt exist' # # - Dealer Branding shares the same primary ID as the Dealer record # - Dealer Contact info shares the same primary ID as the Dealer record data[:id] = id if id payload = { data: data } response = Alula::Client.request(:post, self.class.resource_url, payload, {}) if response.ok? construct_from(response.data['data']) return true end handle_errors(response) end private def handle_errors(response) # Should never see a 300-range response code if (300..399).cover?(response.http_status) raise Alula::UnknownError, "The Alula-Ruby gem encountered a response code of #{response.code}, that should not happen" # Server errors, malformed crap, etc elsif (500..599).cover?(response.http_status) return AlulaError.for_response(response) # Validation errors usually elsif (400..499).cover?(response.http_status) model_errors = Util.model_errors_from_response(response) if model_errors annotate_errors(model_errors) return false else return AlulaError.for_response(response) end else raise Alula::UnknownError, "Unknown HTTP response code, aborting. Code: #{response.http_status}" end end def video_request?(resource_path) resource_path.match(%r{^/video}) end end end end end