From 4e12e9055cf42574a577248542866caaf2a399d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alberto=20Miedes=20Garc=C3=A9s?= Date: Tue, 3 Jan 2017 16:27:11 +0100 Subject: [PATCH] Refactor GraphQL::TypeCreator --- lib/graph_ql/type_creator.rb | 49 ++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/lib/graph_ql/type_creator.rb b/lib/graph_ql/type_creator.rb index aa303ec58..2a4a4ad45 100644 --- a/lib/graph_ql/type_creator.rb +++ b/lib/graph_ql/type_creator.rb @@ -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