Refactor GraphQL::TypeCreator

This commit is contained in:
Alberto Miedes Garcés
2017-01-03 16:27:11 +01:00
parent 2c5925f947
commit 4e12e9055c

View File

@@ -24,29 +24,18 @@ module GraphQL
description("#{model.model_name.human}")
# Make a field for each column, association or method
fields.each do |name, type|
case GraphQL::TypeCreator.type_kind(type)
fields.each do |field_name, field_type|
case TypeCreator.type_kind(field_type)
when :scalar
field name, SCALAR_TYPES[type]
field(field_name, SCALAR_TYPES[field_type])
when :simple_association
field(name, -> { type_creator.created_types[type] }) do
resolve -> (object, arguments, context) do
target_public_elements = type.respond_to?(:public_for_api) ? type.public_for_api : type.all
wanted_element = object.send(name)
if target_public_elements.include?(wanted_element) || GraphQL::TypeCreator.matching_exceptions.include?(name)
wanted_element
else
nil
end
end
field(field_name, -> { type_creator.created_types[field_type] }) do
resolve TypeCreator.create_association_resolver(field_name, field_type)
end
when :paginated_association
type = type.first
connection(name, -> { type_creator.created_types[type].connection_type }) do
resolve -> (object, arguments, context) do
target_public_elements = type.respond_to?(:public_for_api) ? type.public_for_api : type.all
object.send(name).all & target_public_elements.all
end
field_type = field_type.first
connection(field_name, -> { type_creator.created_types[field_type].connection_type }) do
resolve TypeCreator.create_association_resolver(field_name, field_type)
end
end
end
@@ -56,6 +45,28 @@ module GraphQL
return created_type # GraphQL::ObjectType
end
def self.create_association_resolver(field_name, field_type)
-> (object, arguments, context) do
allowed_elements = target_public_elements(field_type)
requested_elements = object.send(field_name)
filter_forbidden_elements(requested_elements, allowed_elements, field_name)
end
end
def self.target_public_elements(field_type)
field_type.respond_to?(:public_for_api) ? field_type.public_for_api : field_type.all
end
def self.filter_forbidden_elements(requested, allowed_elements, field_name=nil)
if field_name && matching_exceptions.include?(field_name)
requested
elsif requested.respond_to?(:each)
requested.all & allowed_elements.all
else
allowed_elements.include?(requested) ? requested : nil
end
end
def self.type_kind(type)
if SCALAR_TYPES[type]
:scalar