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
use crate::validation::visitor::{VisitMode, Visitor, VisitorContext}; use crate::Positioned; use async_graphql_parser::types::Field; 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; use crate::validation::{visit, VisitorContext}; use crate::{EmptyMutation, EmptySubscription, Object, Schema}; struct Query; struct MyObj; #[Object(internal)] impl MyObj { async fn a(&self) -> i32 { 1 } async fn b(&self) -> i32 { 2 } async fn c(&self) -> MyObj { MyObj } } #[Object(internal)] impl Query { async fn value(&self) -> i32 { 1 } async fn obj(&self) -> MyObj { MyObj } } fn check_depth(query: &str, expect_depth: usize) { let registry = Schema::<Query, EmptyMutation, EmptySubscription>::create_registry(); 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, ); } }