Extract TypeCreator methods into AssociationResolver class

This commit is contained in:
Alberto Miedes Garcés
2017-01-03 16:52:13 +01:00
parent 4e12e9055c
commit cdc3b46370
2 changed files with 37 additions and 30 deletions

View File

@@ -0,0 +1,35 @@
module GraphQL
class AssociationResolver
attr_reader :field_name, :target_model, :allowed_elements
def initialize(field_name, target_model)
@field_name = field_name
@target_model = target_model
@allowed_elements = target_public_elements
end
def call(object, arguments, context)
requested_elements = object.send(field_name)
filter_forbidden_elements(requested_elements)
end
def target_public_elements
target_model.respond_to?(:public_for_api) ? target_model.public_for_api : target_model.all
end
def filter_forbidden_elements(requested_elements)
if AssociationResolver.matching_exceptions.include?(field_name)
requested_elements
elsif requested_elements.respond_to?(:each)
requested_elements.all & allowed_elements.all
else
allowed_elements.include?(requested_elements) ? requested_elements : nil
end
end
def self.matching_exceptions
[:public_voter]
end
end
end

View File

@@ -1,6 +1,5 @@
module GraphQL
class TypeCreator
# Return a GraphQL type for a 'database_type'
SCALAR_TYPES = {
integer: GraphQL::INT_TYPE,
boolean: GraphQL::BOOLEAN_TYPE,
@@ -30,12 +29,12 @@ module GraphQL
field(field_name, SCALAR_TYPES[field_type])
when :simple_association
field(field_name, -> { type_creator.created_types[field_type] }) do
resolve TypeCreator.create_association_resolver(field_name, field_type)
resolve GraphQL::AssociationResolver.new(field_name, field_type)
end
when :paginated_association
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)
resolve GraphQL::AssociationResolver.new(field_name, field_type)
end
end
end
@@ -45,28 +44,6 @@ 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
@@ -77,10 +54,5 @@ module GraphQL
end
end
# TODO: esto es una ñapa, hay que buscar una solución mejor
def self.matching_exceptions
[:public_voter]
end
end
end