Skip to content

[6.x] Add ability to exclude queries from graphql cache#14624

Closed
Skullsneeze wants to merge 2 commits into
statamic:6.xfrom
Skullsneeze:6.x
Closed

[6.x] Add ability to exclude queries from graphql cache#14624
Skullsneeze wants to merge 2 commits into
statamic:6.xfrom
Skullsneeze:6.x

Conversation

@Skullsneeze
Copy link
Copy Markdown
Contributor

This PR provides introduces a new option to exclude certain queries from the GraphQL cache. This can be handy if you need to ensure certain data needs to be retrieved in real-time, while keeping the other responses cached.

Related docs PR: statamic/docs#1902

@jasonvarga
Copy link
Copy Markdown
Member

Thanks for the PR! After thinking about this, I'd rather not pull this into core. The "bypass cache for specific fields" use case is niche enough — and opinionated enough (field name? operation name? directive? request header?) — that I think it's better served by letting you swap in your own cache implementation than by trying to support one shape of it in core.

Since Statamic\GraphQL\ResponseCache\DefaultCache is bound to the Statamic\Contracts\GraphQL\ResponseCache contract, so you can rebind it in a service provider with your own subclass:

// app/Providers/AppServiceProvider.php
use Statamic\Contracts\GraphQL\ResponseCache;
use App\GraphQL\SelectiveCache;

public function register()
{
    $this->app->bind(ResponseCache::class, SelectiveCache::class);
}
// app/GraphQL/SelectiveCache.php
namespace App\GraphQL;

use Illuminate\Http\Request;
use Statamic\GraphQL\ResponseCache\DefaultCache;

class SelectiveCache extends DefaultCache
{
    protected array $excluded = ['posts', 'liveScores'];

    public function get(Request $request)
    {
        if ($this->shouldBypass($request->input('query', ''))) {
            return null;
        }

        return parent::get($request);
    }

    public function put(Request $request, $response)
    {
        if ($this->shouldBypass($request->input('query', ''))) {
            return;
        }

        parent::put($request, $response);
    }

    protected function shouldBypass(string $query): bool
    {
        // your AST walk, regex, header check — whatever fits your app
    }
}

That way you get exactly the matching semantics you want (and can handle fragments, aliases, invalid queries, etc. however makes sense for your setup) without us baking one interpretation into core.

Going to close this one out — appreciate you putting it together, and thanks for the docs PR too!

@jasonvarga jasonvarga closed this May 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants