Sha256: a32e96abfedc0b955da89c080236ce7b8a47daf095b4f15ccbb2128eeafe420c

Contents?: true

Size: 1.86 KB

Versions: 14

Compression:

Stored size: 1.86 KB

Contents

# frozen_string_literal: true
module GraphQL
  module Analysis
    # A query reducer for measuring the depth of a given query.
    #
    # @example Logging the depth of a query
    #   class LogQueryDepth < GraphQL::Analysis::QueryDepth
    #     def on_analysis_end
    #       log("GraphQL query depth: #{@max_depth}")
    #     end
    #   end
    #
    #   Schema.execute(query_str)
    #   # GraphQL query depth: 8
    #
    module AST
      class QueryDepth < Analyzer
        def initialize(query)
          @max_depth = 0
          @current_depth = 0
          @skip_depth = 0
          super
        end

        def on_enter_field(node, parent, visitor)
          return if visitor.skipping? || visitor.visiting_fragment_definition?

          # Don't validate introspection fields or skipped nodes
          if GraphQL::Schema::DYNAMIC_FIELDS.include?(visitor.field_definition.name)
            @skip_depth += 1
          elsif @skip_depth > 0
            # we're inside an introspection query or skipped node
          else
            @current_depth += 1
          end
        end

        def on_leave_field(node, parent, visitor)
          return if visitor.skipping? || visitor.visiting_fragment_definition?

          # Don't validate introspection fields or skipped nodes
          if GraphQL::Schema::DYNAMIC_FIELDS.include?(visitor.field_definition.name)
            @skip_depth -= 1
          else
            if @max_depth < @current_depth
              @max_depth = @current_depth
            end
            @current_depth -= 1
          end
        end

        def on_enter_fragment_spread(node, _, visitor)
          visitor.enter_fragment_spread_inline(node)
        end

        def on_leave_fragment_spread(node, _, visitor)
          visitor.leave_fragment_spread_inline(node)
        end

        def result
          @max_depth
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
graphql-1.9.9 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.8 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.7 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.6 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.5 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.4 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.3 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.2 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.1 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.0 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.0.pre4 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.0.pre3 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.0.pre2 lib/graphql/analysis/ast/query_depth.rb
graphql-1.9.0.pre1 lib/graphql/analysis/ast/query_depth.rb