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 for postCollection
and post
for 120 + 10
seconds. When a Post
is mutated, the corresponding tag
(id
of the product) will get invalidated.
import { config, g } from '@grafbase/sdk'
export default config({
schema: g,
cache: {
rules: [
{
maxAge: 120,
staleWhileRevalidate: 60,
types: ['Post'],
mutationInvalidation: 'entity',
},
{
maxAge: 10,
staleWhileRevalidate: 10,
types: [{ name: 'Query', fields: ['postCollection', 'post'] }],
},
],
},
})
The new mutationInvalidation
property accepts multiple options, and works when configuring cachine globally or per type/database model:
entity
— Triggered by mutations for the specified type, this will invalidate any cache entry containing the selected field. 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, g } from '@grafbase/sdk'
export default config({
schema: g,
cache: {
rules: [
{ maxAge: 10, types: "Product", mutationInvalidation: {
field: '_id'
} },
{
maxAge: 10
types: [{ name: "Query", fields: ["products", "product"] }]
}
]
}
})
The lowest maxAge
value wins.