6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
# File 'lib/graphql/static_validation/rules/document_does_not_exceed_max_depth.rb', line 6
def validate(context)
max_allowed_depth = context.query.max_depth
return if max_allowed_depth.nil?
visitor = context.visitor
current_field_scope = nil
current_depth = 0
skip_current_scope = false
depths = Hash.new { |h, k| h[k] = 0 }
fragments = Hash.new { |h, k| h[k] = []}
visitor[GraphQL::Language::Nodes::Document].leave << -> (node, parent) {
context.errors.none? && assert_under_max_depth(context, max_allowed_depth, depths, fragments)
}
visitor[GraphQL::Language::Nodes::OperationDefinition] << -> (node, parent) {
current_field_scope = node.name
}
visitor[GraphQL::Language::Nodes::FragmentDefinition] << -> (node, parent) {
current_field_scope = node.name
}
visitor[GraphQL::Language::Nodes::Field] << -> (node, parent) {
skip_current_scope ||= context.skip_field?(node.name)
if node.selections.any? && !skip_current_scope
current_depth += 1
if current_depth > depths[current_field_scope]
depths[current_field_scope] = current_depth
end
end
}
visitor[GraphQL::Language::Nodes::Field].leave << -> (node, parent) {
if skip_current_scope && context.skip_field?(node.name)
skip_current_scope = false
elsif node.selections.any?
current_depth -= 1
end
}
visitor [GraphQL::Language::Nodes::FragmentSpread] << -> (node, parent) {
fragments[current_field_scope] << node.name
}
end
|