Skip to content

Commit

Permalink
Merge pull request #1174 from johnmosesman/release-0-9
Browse files Browse the repository at this point in the history
Cherrypicks into 0.9 - fixes #909 add possibility to set generic validation error
  • Loading branch information
lgebhardt authored Aug 30, 2018
2 parents 3707e8c + bb2f983 commit bb95f67
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/jsonapi/exceptions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -448,11 +448,12 @@ def errors
end

class ValidationErrors < Error
attr_reader :error_messages, :error_metadata, :resource_relationships
attr_reader :error_messages, :error_metadata, :resource_relationships, :resource_class

def initialize(resource, error_object_overrides = {})
@error_messages = resource.model_error_messages
@error_metadata = resource.validation_error_metadata
@resource_class = resource.class
@resource_relationships = resource.class._relationships.keys
@key_formatter = JSONAPI.configuration.key_formatter
super(error_object_overrides)
Expand All @@ -474,7 +475,7 @@ def json_api_error(attr_key, message)
create_error_object(code: JSONAPI::VALIDATION_ERROR,
status: :unprocessable_entity,
title: message,
detail: "#{format_key(attr_key)} - #{message}",
detail: detail(attr_key, message),
source: { pointer: pointer(attr_key) },
meta: metadata_for(attr_key, message))
end
Expand All @@ -484,14 +485,23 @@ def metadata_for(attr_key, message)
error_metadata[attr_key] ? error_metadata[attr_key][message] : nil
end

def detail(attr_key, message)
general_error?(attr_key) ? message : "#{format_key(attr_key)} - #{message}"
end

def pointer(attr_or_relationship_name)
return '/data' if general_error?(attr_or_relationship_name)
formatted_attr_or_relationship_name = format_key(attr_or_relationship_name)
if resource_relationships.include?(attr_or_relationship_name)
"/data/relationships/#{formatted_attr_or_relationship_name}"
else
"/data/attributes/#{formatted_attr_or_relationship_name}"
end
end

def general_error?(attr_key)
attr_key.to_sym == :base && !resource_class._has_attribute?(attr_key)
end
end

class SaveFailed < Error
Expand Down
4 changes: 4 additions & 0 deletions lib/jsonapi/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,10 @@ def _attribute_options(attr)
default_attribute_options.merge(@_attributes[attr])
end

def _has_attribute?(attr)
@_attributes.keys.include?(attr.to_sym)
end

def _updatable_relationships
@_relationships.map { |key, _relationship| key }
end
Expand Down

0 comments on commit bb95f67

Please sign in to comment.