Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions config/graphql.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@

'cache' => [
'expiry' => 60,
'exclude' => [],
],

];
51 changes: 51 additions & 0 deletions src/GraphQL/ResponseCache/DefaultCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Statamic\GraphQL\ResponseCache;

use GraphQL\Language\AST\FieldNode;
use GraphQL\Language\Parser;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
Expand All @@ -12,6 +14,10 @@ class DefaultCache implements ResponseCache
{
public function get(Request $request)
{
if ($this->shouldBypassCache($request->input('query'))) {
return null;
}

return Cache::get($this->getCacheKey($request));
}

Expand Down Expand Up @@ -66,4 +72,49 @@ public function handleInvalidationEvent(Event $event)

Cache::forget($this->getTrackingKey());
}

public function shouldBypassCache(string $query): bool
{
$excludedQueries = config('statamic.graphql.cache.exclude', []);
if (!$excludedQueries) {
return false;
}

$ast = Parser::parse($query);

foreach ($ast->definitions as $definition) {
if (!isset($definition->selectionSet)) {
continue;
}

foreach (array_keys($excludedQueries) as $excludedQuery) {
foreach ($definition->selectionSet->selections as $selection) {
if ($this->containsFieldRecursive($selection, $excludedQuery)) {
return true;
}
}
}
}

return false;
}

private function containsFieldRecursive($node, string $fieldName): bool
{
if ($node instanceof FieldNode) {
if ($node->name->value === $fieldName) {
return true;
}

if ($node->selectionSet) {
foreach ($node->selectionSet->selections as $selection) {
if ($this->containsFieldRecursive($selection, $fieldName)) {
return true;
}
}
}
}

return false;
}
}
Loading