Sha256: 9acec26ab1961bef8779382314257ab6e4bdb2dd1bb0b4d67c86d3975c7b0147

Contents?: true

Size: 1.63 KB

Versions: 1

Compression:

Stored size: 1.63 KB

Contents

# frozen_string_literal: true
module GraphQL
  module Analysis
    # A query reducer for measuring the depth of a given query.
    #
    # See https://graphql-ruby.org/queries/ast_analysis.html for more examples.
    #
    # @example Logging the depth of a query
    #   class LogQueryDepth < GraphQL::Analysis::QueryDepth
    #     def result
    #       log("GraphQL query depth: #{@max_depth}")
    #     end
    #   end
    #
    #   # In your Schema file:
    #
    #   class MySchema < GraphQL::Schema
    #     use GraphQL::Analysis::AST
    #     query_analyzer LogQueryDepth
    #   end
    #
    #   # When you run the query, the depth will get logged:
    #
    #   Schema.execute(query_str)
    #   # GraphQL query depth: 8
    #
    module AST
      class QueryDepth < Analyzer
        def initialize(query)
          @max_depth = 0
          @current_depth = 0
          super
        end

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

          @current_depth += 1
        end

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

          if @max_depth < @current_depth
            @max_depth = @current_depth
          end
          @current_depth -= 1
        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

1 entries across 1 versions & 1 rubygems

Version Path
graphql-1.9.11 lib/graphql/analysis/ast/query_depth.rb