Skip to content

Add an option to allow include on a relationship #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/jsonapi-serializers/attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ def add_attribute(name, options = {}, &block)
def add_to_one_association(name, options = {}, &block)
options[:include_links] = options.fetch(:include_links, true)
options[:include_data] = options.fetch(:include_data, false)
options[:allow_include] = options.fetch(:allow_include, true)
@to_one_associations ||= {}
@to_one_associations[name] = {
attr_or_block: block_given? ? block : name,
Expand All @@ -65,6 +66,7 @@ def add_to_one_association(name, options = {}, &block)
def add_to_many_association(name, options = {}, &block)
options[:include_links] = options.fetch(:include_links, true)
options[:include_data] = options.fetch(:include_data, false)
options[:allow_include] = options.fetch(:allow_include, true)
@to_many_associations ||= {}
@to_many_associations[name] = {
attr_or_block: block_given? ? block : name,
Expand Down
71 changes: 45 additions & 26 deletions lib/jsonapi-serializers/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ def relationships
else
related_object_serializer = JSONAPI::Serializer.find_serializer(object, @options)
data[formatted_attribute_name]['data'] = {
'type' => related_object_serializer.type.to_s,
'id' => related_object_serializer.id.to_s,
'type' => related_object_serializer.type.to_s,
'id' => related_object_serializer.id.to_s,
}
end
end
Expand Down Expand Up @@ -147,8 +147,8 @@ def relationships
objects.each do |obj|
related_object_serializer = JSONAPI::Serializer.find_serializer(obj, @options)
data[formatted_attribute_name]['data'] << {
'type' => related_object_serializer.type.to_s,
'id' => related_object_serializer.id.to_s,
'type' => related_object_serializer.type.to_s,
'id' => related_object_serializer.id.to_s,
}
end
end
Expand Down Expand Up @@ -202,6 +202,7 @@ def should_include_attr?(if_method_name, unless_method_name)
show_attr &&= !send(unless_method_name) if unless_method_name
show_attr
end

protected :should_include_attr?

def evaluate_attr_or_block(attribute_name, attr_or_block)
Expand All @@ -213,6 +214,7 @@ def evaluate_attr_or_block(attribute_name, attr_or_block)
object.send(attr_or_block)
end
end

protected :evaluate_attr_or_block
end

Expand Down Expand Up @@ -251,15 +253,15 @@ def self.serialize(objects, options = {})

# An internal-only structure that is passed through serializers as they are created.
passthrough_options = {
context: options[:context],
serializer: options[:serializer],
include: includes,
base_url: options[:base_url]
context: options[:context],
serializer: options[:serializer],
include: includes,
base_url: options[:base_url]
}

if !options[:skip_collection_check] && options[:is_collection] && !objects.respond_to?(:each)
raise JSONAPI::Serializer::AmbiguousCollectionError.new(
'Attempted to serialize a single object as a collection.')
'Attempted to serialize a single object as a collection.')
end

# Automatically include linkage data for any relation that is also included.
Expand All @@ -285,13 +287,13 @@ def self.serialize(objects, options = {})
# how to serialize null single resources vs. empty collections.
if !options[:skip_collection_check] && objects.respond_to?(:each)
raise JSONAPI::Serializer::AmbiguousCollectionError.new(
'Must provide `is_collection: true` to `serialize` when serializing collections.')
'Must provide `is_collection: true` to `serialize` when serializing collections.')
end
# Have single object.
primary_data = serialize_primary(objects, passthrough_options)
end
result = {
'data' => primary_data,
'data' => primary_data,
}
result['meta'] = options[:meta] if options[:meta]
result['errors'] = options[:errors] if options[:errors]
Expand Down Expand Up @@ -342,10 +344,10 @@ def self.is_activemodel_errors?(raw_errors)

def self.single_error(attribute, message)
{
'source' => {
'pointer' => "/data/attributes/#{attribute.dasherize}"
},
'detail' => message
'source' => {
'pointer' => "/data/attributes/#{attribute.dasherize}"
},
'detail' => message
}
end

Expand All @@ -359,8 +361,8 @@ def self.serialize_primary(object, options = {})

serializer = serializer_class.new(object, options)
data = {
'id' => serializer.id.to_s,
'type' => serializer.type.to_s,
'id' => serializer.id.to_s,
'type' => serializer.type.to_s,
}

# Merge in optional top-level members if they are non-nil.
Expand All @@ -376,7 +378,10 @@ def self.serialize_primary(object, options = {})
data['meta'] = meta if !meta.nil?
data
end
class << self; protected :serialize_primary; end

class << self;
protected :serialize_primary;
end

def self.serialize_primary_multi(objects, options = {})
# Spec: Primary data MUST be either:
Expand All @@ -386,7 +391,10 @@ def self.serialize_primary_multi(objects, options = {})

objects.map { |obj| serialize_primary(obj, options) }
end
class << self; protected :serialize_primary_multi; end

class << self;
protected :serialize_primary_multi;
end

# Recursively find object relationships and returns a tree of related objects.
# Example return:
Expand All @@ -409,26 +417,28 @@ def self.find_recursive_relationships(root_object, root_inclusion_tree, results,
is_collection = false
is_valid_attr = false
if serializer.has_one_relationships.has_key?(unformatted_attr_name)
is_valid_attr = true
# Only valid include if relationship is allowed to be included
is_valid_attr = serializer.has_one_relationships[unformatted_attr_name][:options][:allow_include]
attr_data = serializer.has_one_relationships[unformatted_attr_name]
object = serializer.has_one_relationship(unformatted_attr_name, attr_data)
elsif serializer.has_many_relationships.has_key?(unformatted_attr_name)
is_valid_attr = true
# Only valid include if relationship is allowed to be included
is_valid_attr = serializer.has_many_relationships[unformatted_attr_name][:options][:allow_include]
is_collection = true
attr_data = serializer.has_many_relationships[unformatted_attr_name]
object = serializer.has_many_relationship(unformatted_attr_name, attr_data)
end

if !is_valid_attr
raise JSONAPI::Serializer::InvalidIncludeError.new(
"'#{attribute_name}' is not a valid include.")
"'#{attribute_name}' is not a valid include.")
end

if attribute_name != serializer.format_name(attribute_name)
expected_name = serializer.format_name(attribute_name)

raise JSONAPI::Serializer::InvalidIncludeError.new(
"'#{attribute_name}' is not a valid include. Did you mean '#{expected_name}' ?"
"'#{attribute_name}' is not a valid include. Did you mean '#{expected_name}' ?"
)
end

Expand Down Expand Up @@ -483,7 +493,10 @@ def self.find_recursive_relationships(root_object, root_inclusion_tree, results,
end
nil
end
class << self; protected :find_recursive_relationships; end

class << self;
protected :find_recursive_relationships;
end

# Takes a list of relationship paths and returns a hash as deep as the given paths.
# The _include: true is a sentinal value that specifies whether the parent level should
Expand All @@ -500,7 +513,10 @@ def self.parse_relationship_paths(paths)
paths.each { |path| merge_relationship_path(path, relationships) }
relationships
end
class << self; protected :parse_relationship_paths; end

class << self;
protected :parse_relationship_paths;
end

def self.merge_relationship_path(path, data)
parts = path.split('.', 2)
Expand All @@ -512,6 +528,9 @@ def self.merge_relationship_path(path, data)
merge_relationship_path(parts[1], data[current_level])
end
end
class << self; protected :merge_relationship_path; end

class << self;
protected :merge_relationship_path;
end
end
end
7 changes: 7 additions & 0 deletions spec/serializer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,13 @@ def read_attribute_for_validation(attr)
expect { JSONAPI::Serializer.serialize(post, include: ['long_comments']) }.to raise_error(error)
end

it 'raises error if include is not allowed on relationship' do
hidden_permission = create(:hidden_permission, :with_user)
user = hidden_permission.user
error = JSONAPI::Serializer::InvalidIncludeError
expect { JSONAPI::Serializer.serialize(user, include: ['hidden_permissions']) }.to raise_error(error)
end

it 'can serialize a nil object when given serializer' do
options = {serializer: MyApp::PostSerializer}
expect(JSONAPI::Serializer.serialize(nil, options)).to eq({'data' => nil})
Expand Down
10 changes: 10 additions & 0 deletions spec/support/factory.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@
sequence(:name) {|n| "User ##{n}"}
end

factory :hidden_permission, class: MyApp::HiddenPermission do
skip_create
sequence(:id) {|n| n }
sequence(:permission) {|n| "Permission ##{n}"}

trait :with_user do
association :user, factory: :user
end
end

factory :underscore_test, class: MyApp::UnderscoreTest do
skip_create
sequence(:id) {|n| n }
Expand Down
13 changes: 13 additions & 0 deletions spec/support/serializers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ def jsonapi_serializer_class_name
end
end

class HiddenPermission
attr_accessor :id
attr_accessor :permission
attr_accessor :user
end

class UnderscoreTest
attr_accessor :id

Expand Down Expand Up @@ -220,6 +226,13 @@ class PostSerializerWithInheritedProperties < PostSerializer
# Add only :tag, inherit the rest.
attribute :tag
end

class HiddenPermissionSerializer
include JSONAPI::Serializer
attribute :permission

has_one :user, allow_include: false
end
end

# Test the `jsonapi_serializer_class_name` override method for serializers in different namespaces.
Expand Down