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: AbstractTypeComplexity, ConcreteTypeComplexity

Instance Method Summary collapse

Methods inherited from Analyzer

#analyze?

Constructor Details

#initialize(query) ⇒ QueryComplexity

State for the query complexity calculation: - complexities_on_type holds complexity scores for each type in an IRep node



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

def initialize(query)
  super
  @complexities_on_type = [ConcreteTypeComplexity.new]
end

Instance Method Details

#max_possible_complexityInteger

Returns:

  • (Integer)


54
55
56
# File 'lib/graphql/analysis/ast/query_complexity.rb', line 54

def max_possible_complexity
  @complexities_on_type.last.max_possible_complexity
end

#on_enter_field(node, parent, visitor) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/graphql/analysis/ast/query_complexity.rb', line 19

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?

  if visitor.type_definition.kind.abstract?
    @complexities_on_type.push(AbstractTypeComplexity.new)
  else
    @complexities_on_type.push(ConcreteTypeComplexity.new)
  end
end

#on_leave_field(node, parent, visitor) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/graphql/analysis/ast/query_complexity.rb', line 32

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?

  type_complexities = @complexities_on_type.pop
  child_complexity = type_complexities.max_possible_complexity
  own_complexity = get_complexity(node, visitor.field_definition, child_complexity, visitor)

  if @complexities_on_type.last.is_a?(AbstractTypeComplexity)
    key = selection_key(visitor.response_path, visitor.query)
    parent_type = visitor.parent_type_definition
    visitor.query.possible_types(parent_type).each do |type|
      @complexities_on_type.last.merge(type, key, own_complexity)
    end
  else
    @complexities_on_type.last.merge(own_complexity)
  end
end

#resultObject

Overide this method to use the complexity result



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

def result
  max_possible_complexity
end