Class: GraphQL::Analysis::AST::QueryComplexity

Inherits:
Analyzer
  • Object
show all
Defined in:
lib/graphql/analysis/ast/query_complexity.rb

Direct Known Subclasses

MaxQueryComplexity

Defined Under Namespace

Classes: ScopedTypeComplexity

Instance Method Summary collapse

Methods inherited from Analyzer

#analyze?, #visit?

Constructor Details

#initialize(query) ⇒ QueryComplexity

State for the query complexity calculation: - complexities_on_type holds complexity scores for each type



9
10
11
12
13
# File 'lib/graphql/analysis/ast/query_complexity.rb', line 9

def initialize(query)
  super
  @skip_introspection_fields = !query.schema.max_complexity_count_introspection_fields
  @complexities_on_type_by_query = {}
end

Instance Method Details

#on_enter_field(node, parent, visitor) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/graphql/analysis/ast/query_complexity.rb', line 50

def on_enter_field(node, parent, visitor)
  # We don't want to visit fragment definitions,
  # we'll visit them when we hit the spreads instead
  return if visitor.visiting_fragment_definition?
  return if visitor.skipping?
  return if @skip_introspection_fields && visitor.field_definition.introspection?
  parent_type = visitor.parent_type_definition
  field_key = node.alias || node.name

  # Find or create a complexity scope stack for this query.
  scopes_stack = @complexities_on_type_by_query[visitor.query] ||= [ScopedTypeComplexity.new(nil, nil, query, visitor.response_path)]

  # Find or create the complexity costing node for this field.
  scope = scopes_stack.last[parent_type][field_key] ||= ScopedTypeComplexity.new(parent_type, visitor.field_definition, visitor.query, visitor.response_path)
  scope.nodes.push(node)
  scopes_stack.push(scope)
end

#on_leave_field(node, parent, visitor) ⇒ Object



68
69
70
71
72
73
74
75
76
# File 'lib/graphql/analysis/ast/query_complexity.rb', line 68

def on_leave_field(node, parent, visitor)
  # We don't want to visit fragment definitions,
  # we'll visit them when we hit the spreads instead
  return if visitor.visiting_fragment_definition?
  return if visitor.skipping?
  return if @skip_introspection_fields && visitor.field_definition.introspection?
  scopes_stack = @complexities_on_type_by_query[visitor.query]
  scopes_stack.pop
end

#resultObject

Overide this method to use the complexity result



16
17
18
# File 'lib/graphql/analysis/ast/query_complexity.rb', line 16

def result
  max_possible_complexity
end