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: TypeComplexity

Instance Method Summary collapse

Methods inherited from Analyzer

#analyze?, build_visitor_hooks

Constructor Details

#initialize(query) ⇒ QueryComplexity

State for the query complexity calcuation: - 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 = [TypeComplexity.new]
end

Instance Method Details

#max_possible_complexityInteger

Returns:

  • (Integer)


61
62
63
# File 'lib/graphql/analysis/ast/query_complexity.rb', line 61

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
# 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?

  @complexities_on_type.push(TypeComplexity.new)
end

#on_enter_fragment_spread(node, _, visitor) ⇒ Object



52
53
54
# File 'lib/graphql/analysis/ast/query_complexity.rb', line 52

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

#on_leave_field(node, parent, visitor) ⇒ Object



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

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)

  parent_type = visitor.parent_type_definition
  possible_types = if parent_type.kind.abstract?
    query.possible_types(parent_type)
  else
    [parent_type]
  end

  key = selection_key(visitor.response_path, visitor.query)

  possible_types.each do |type|
    @complexities_on_type.last.merge(type, key, own_complexity)
  end
end

#on_leave_fragment_spread(node, _, visitor) ⇒ Object



56
57
58
# File 'lib/graphql/analysis/ast/query_complexity.rb', line 56

def on_leave_fragment_spread(node, _, visitor)
  visitor.leave_fragment_spread_inline(node)
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