Cache Rules
The configuration for caching rules are outlined below:
The types
field is required for caching responses and allows targeting specific types.
It supports three formats: a single String
for a single type, an array of String
for multiple types, or a structured array of rules for targeting fields and types.
import { config } from '@grafbase/sdk'
export default config({
cache: {
rules: [
{
types: ['Post'],
},
],
},
})
Use the maxAge
value to specify how long (in seconds) the cached entry is considered to be fresh.
import { config } from '@grafbase/sdk'
export default config({
cache: {
rules: [
{
maxAge: 60,
},
],
},
})
The lowest value for maxAge
always wins for nested cache rules.
Use the staleWhileRevalidate
value to specify how long (in seconds) the cached entry is considered to be stale.
import { config } from '@grafbase/sdk'
export default config({
cache: {
rules: [
{
maxAge: 30,
staleWhileRevalidate: 60,
},
],
},
})
The mutationInvalidation
strategy provides a robust method for purging cached entries associated with specific tags. When implemented, the Edge Gateway scrutinizes GraphQL query responses to extract necessary data, consequently adorning the cache entries with appropriate tags.
To configure mutationInvalidation
, simply add the optional mutationInvalidation
attribute and value. The mutation response will then trigger a purge for any cache entry referencing the mutated type.
In the example below, Grafbase will cache responses with Post
for 120 + 60
seconds. When a Post
is mutated, any cached response with Post#id:mutated_post_id
(cache tag) will get invalidated.
import { config, graph } from '@grafbase/sdk'
const g = graph.Standalone()
export default config({
graph: g,
cache: {
rules: [
{
maxAge: 120,
staleWhileRevalidate: 60,
types: ['Post'],
mutationInvalidation: 'entity',
},
],
},
})
The new mutationInvalidation
property accepts multiple options:
entity
— Triggered by mutations for the specified type, this will invalidate any cache entry containing the selected field of the type. By default, it utilizes theid
.list
— Triggered by mutations for the specified type, this will invalidate any cache entry containing lists of the corresponding type.type
— Triggered by mutations for the specified type, this will invalidate any cache entry containing the type.
By default the cache uses the id
to tag entities. If you need to specify a field that is something else, you can do that by passing an object to the mutationInvalidation
field:
import { config, graph } from '@grafbase/sdk'
const g = graph.Standalone()
export default config({
graph: g,
cache: {
rules: [
{ maxAge: 10, types: "Product", mutationInvalidation: {
field: '_id'
} },
{
maxAge: 10
types: [{ name: "Query", fields: ["products", "product"] }]
}
]
}
})
mutationInvalidation
is type specific and is not recursive.
The recommended way to think about this field, and strategy, is from a fined grained perspective targeting specific types.
The lowest maxAge
value wins.