Skip to content

Commit e1643b7

Browse files
committed
Add possibility to bypass graphql cache
1 parent 364df0f commit e1643b7

2 files changed

Lines changed: 52 additions & 0 deletions

File tree

config/graphql.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@
9898

9999
'cache' => [
100100
'expiry' => 60,
101+
'exclude' => [],
101102
],
102103

103104
/*

src/GraphQL/ResponseCache/DefaultCache.php

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace Statamic\GraphQL\ResponseCache;
44

5+
use GraphQL\Language\AST\FieldNode;
6+
use GraphQL\Language\Parser;
57
use Illuminate\Http\JsonResponse;
68
use Illuminate\Http\Request;
79
use 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

Comments
 (0)