22
33namespace Statamic \GraphQL \ResponseCache ;
44
5+ use GraphQL \Language \AST \FieldNode ;
6+ use GraphQL \Language \Parser ;
57use Illuminate \Http \JsonResponse ;
68use Illuminate \Http \Request ;
79use Illuminate \Support \Carbon ;
@@ -13,6 +15,10 @@ class DefaultCache implements ResponseCache
1315{
1416 public function get (Request $ request )
1517 {
18+ if ($ this ->shouldBypassCache ($ request ->input ('query ' ))) {
19+ return null ;
20+ }
21+
1622 $ cached = Cache::get ($ this ->getCacheKey ($ request ));
1723
1824 if (! is_array ($ cached )) {
@@ -77,4 +83,49 @@ public function handleInvalidationEvent(Event $event)
7783
7884 Cache::forget ($ this ->getTrackingKey ());
7985 }
86+
87+ public function shouldBypassCache (string $ query ): bool
88+ {
89+ $ excludedQueries = config ('statamic.graphql.cache.exclude ' , []);
90+ if (! $ excludedQueries ) {
91+ return false ;
92+ }
93+
94+ $ ast = Parser::parse ($ query );
95+
96+ foreach ($ ast ->definitions as $ definition ) {
97+ if (! isset ($ definition ->selectionSet )) {
98+ continue ;
99+ }
100+
101+ foreach (array_keys ($ excludedQueries ) as $ excludedQuery ) {
102+ foreach ($ definition ->selectionSet ->selections as $ selection ) {
103+ if ($ this ->containsFieldRecursive ($ selection , $ excludedQuery )) {
104+ return true ;
105+ }
106+ }
107+ }
108+ }
109+
110+ return false ;
111+ }
112+
113+ private function containsFieldRecursive ($ node , string $ fieldName ): bool
114+ {
115+ if ($ node instanceof FieldNode) {
116+ if ($ node ->name ->value === $ fieldName ) {
117+ return true ;
118+ }
119+
120+ if ($ node ->selectionSet ) {
121+ foreach ($ node ->selectionSet ->selections as $ selection ) {
122+ if ($ this ->containsFieldRecursive ($ selection , $ fieldName )) {
123+ return true ;
124+ }
125+ }
126+ }
127+ }
128+
129+ return false ;
130+ }
80131}
0 commit comments