Sha256: 03d95a2dc8054761e775ee08a7fd75ec77ced9f148503fa39a83a31591a972cf

Contents?: true

Size: 1.44 KB

Versions: 7

Compression:

Stored size: 1.44 KB

Contents

# frozen_string_literal: true
module GraphQL
  module StaticValidation
    class FragmentsAreFinite
      include GraphQL::StaticValidation::Message::MessageHelper

      def validate(context)
        context.visitor[GraphQL::Language::Nodes::FragmentDefinition] << ->(node, parent) {
          if has_nested_spread?(node, [], context)
            context.errors << message("Fragment #{node.name} contains an infinite loop", node, context: context)
          end
        }
      end

      private

      def has_nested_spread?(fragment_def, parent_fragment_names, context)
        nested_spreads = get_spreads(fragment_def.selections)

        nested_spreads.any? do |spread|
          nested_def = context.fragments[spread.name]
          if nested_def.nil?
            # this is another kind of error
            false
          else
            parent_fragment_names.include?(spread.name) || has_nested_spread?(nested_def, parent_fragment_names + [fragment_def.name], context)
          end
        end
      end

      # Find spreads contained in this selection & return them in a flat array
      def get_spreads(selection)
        case selection
        when GraphQL::Language::Nodes::FragmentSpread
          [selection]
        when GraphQL::Language::Nodes::Field, GraphQL::Language::Nodes::InlineFragment
          get_spreads(selection.selections)
        when Array
          selection.map { |s| get_spreads(s) }.flatten
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
graphql-1.4.5 lib/graphql/static_validation/rules/fragments_are_finite.rb
graphql-1.4.4 lib/graphql/static_validation/rules/fragments_are_finite.rb
graphql-1.4.3 lib/graphql/static_validation/rules/fragments_are_finite.rb
graphql-1.4.2 lib/graphql/static_validation/rules/fragments_are_finite.rb
graphql-1.4.1 lib/graphql/static_validation/rules/fragments_are_finite.rb
graphql-1.4.0 lib/graphql/static_validation/rules/fragments_are_finite.rb
graphql-1.3.0 lib/graphql/static_validation/rules/fragments_are_finite.rb