1
2
3
4
5
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
use async_graphql_parser::types::Field;
use crate::{
validation::visitor::{VisitMode, Visitor, VisitorContext},
Positioned,
};
pub struct DepthCalculate<'a> {
max_depth: &'a mut usize,
current_depth: usize,
}
impl<'a> DepthCalculate<'a> {
pub fn new(max_depth: &'a mut usize) -> Self {
Self {
max_depth,
current_depth: 0,
}
}
}
impl<'ctx, 'a> Visitor<'ctx> for DepthCalculate<'a> {
fn mode(&self) -> VisitMode {
VisitMode::Inline
}
fn enter_field(&mut self, _ctx: &mut VisitorContext<'ctx>, _field: &'ctx Positioned<Field>) {
self.current_depth += 1;
*self.max_depth = (*self.max_depth).max(self.current_depth);
}
fn exit_field(&mut self, _ctx: &mut VisitorContext<'ctx>, _field: &'ctx Positioned<Field>) {
self.current_depth -= 1;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
parser::parse_query,
validation::{visit, VisitorContext},
EmptyMutation, EmptySubscription, Object, Schema,
};
struct Query;
struct MyObj;
#[Object(internal)]
#[allow(unreachable_code)]
impl MyObj {
async fn a(&self) -> i32 {
todo!()
}
async fn b(&self) -> i32 {
todo!()
}
async fn c(&self) -> MyObj {
todo!()
}
}
#[Object(internal)]
#[allow(unreachable_code)]
impl Query {
async fn value(&self) -> i32 {
todo!()
}
async fn obj(&self) -> MyObj {
todo!()
}
}
fn check_depth(query: &str, expect_depth: usize) {
let registry =
Schema::<Query, EmptyMutation, EmptySubscription>::create_registry(Default::default());
let doc = parse_query(query).unwrap();
let mut ctx = VisitorContext::new(®istry, &doc, None);
let mut depth = 0;
let mut depth_calculate = DepthCalculate::new(&mut depth);
visit(&mut depth_calculate, &mut ctx, &doc);
assert_eq!(depth, expect_depth);
}
#[test]
fn depth() {
check_depth(
r#"{
value #1
}"#,
1,
);
check_depth(
r#"
{
obj { #1
a b #2
}
}"#,
2,
);
check_depth(
r#"
{
obj { # 1
a b c { # 2
a b c { # 3
a b # 4
}
}
}
}"#,
4,
);
check_depth(
r#"
fragment A on MyObj {
a b ... A2 #2
}
fragment A2 on MyObj {
obj {
a #3
}
}
query {
obj { # 1
... A
}
}"#,
3,
);
check_depth(
r#"
{
obj { # 1
... on MyObj {
a b #2
... on MyObj {
obj {
a #3
}
}
}
}
}"#,
3,
);
}
}