Sha256: a89ff01353999b68394d839d28e92a62fb453dfdd4cc62c94bf614f1cc1bf67a

Contents?: true

Size: 1.65 KB

Versions: 25

Compression:

Stored size: 1.65 KB

Contents

class GraphQL::StaticValidation::FragmentSpreadsArePossible
  include GraphQL::StaticValidation::Message::MessageHelper

  def validate(context)

    context.visitor[GraphQL::Language::Nodes::InlineFragment] << -> (node, parent) {
      fragment_parent = context.object_types[-2]
      fragment_child = context.object_types.last
      validate_fragment_in_scope(fragment_parent, fragment_child, node, context)
    }

    spreads_to_validate = []

    context.visitor[GraphQL::Language::Nodes::FragmentSpread] << -> (node, parent) {
      fragment_parent = context.object_types.last
      spreads_to_validate << [node, fragment_parent]
    }

    context.visitor[GraphQL::Language::Nodes::Document].leave << -> (node, parent) {
      spreads_to_validate.each do |spread_values|
        node, fragment_parent = spread_values
        fragment_child_name = context.fragments[node.name].type
        fragment_child = context.schema.types[fragment_child_name]
        validate_fragment_in_scope(fragment_parent, fragment_child, node, context)
      end
    }
  end

  private

  def validate_fragment_in_scope(parent_type, child_type, node, context)
    intersecting_types = get_possible_types(parent_type) & get_possible_types(child_type)
    if intersecting_types.none?
      name = node.respond_to?(:name) ? " #{node.name}" : ""
      context.errors << message("Fragment#{name} on #{child_type.name} can't be spread inside #{parent_type.name}", node)
    end
  end

  def get_possible_types(type)
    if type.kind.wraps?
      get_possible_types(type.of_type)
    elsif type.kind.object?
      [type]
    elsif type.kind.resolves?
      type.possible_types
    else
      []
    end
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
graphql-0.7.1 lib/graphql/static_validation/rules/fragment_spreads_are_possible.rb
graphql-0.7.0 lib/graphql/static_validation/rules/fragment_spreads_are_possible.rb
graphql-0.6.2 lib/graphql/static_validation/rules/fragment_spreads_are_possible.rb
graphql-0.6.1 lib/graphql/static_validation/rules/fragment_spreads_are_possible.rb
graphql-0.6.0 lib/graphql/static_validation/rules/fragment_spreads_are_possible.rb