Caching cart data
Learn how to cache your customer's cart data.
How to enable cart caching
To enable cart caching, you need to set the environment variable
FRONT_COMMERCE_CART_CACHE_ENABLE
to true
.
Cart will be cached as soon as a call is made to the cart query.
Please note that the cart cache functionality is only available for authenticated customers.
Cache invalidation operations
The cart cache has a TTL of 5 minutes, however some mutations will invalidate the cache immediately. Each extension handle invalidation for its native features.
Automatic cache invalidation using decorateWithCartCacheExpire
In addition to the automated cache system, you might have manipulate the Cart
cache using the decorateWithCartCacheExpire
function.
This function will allow you to decorate a resolver with a function that will invalidate cache.
You can see an example of it's usage in the Gezy Cart Cache Loader
Advanced cache invalidation using CartCache
loader
In addition to the automated cache system, you can also manipulate the Cart
cache using the CartCache
loader.
Let's explain this with an example, imagine you want to invalidate the cart
cache in a mutation. In your resolver, you can call the CartCache
loader to
invalidate the cache:
import { createGraphQLRuntime } from "@front-commerce/core/graphql";
export default createGraphQLRuntime({
resolvers: {
Mutation: {
myCustomMutation: (_, { cartId }, { loaders }) => {
loaders.CartCache.expire(cartId);
},
},
},
});
In this example, myCustomMutation
will invalidate the cart cache for the given
cartId
.
You can also use the CartCache
loader to cache cart with custom query:
import { createGraphQLRuntime } from "@front-commerce/core/graphql";
export default createGraphQLRuntime({
resolvers: {
Query: {
myCustomQuery: (_, { cartId }, { loaders }) => {
return loaders.CartCache.cache(
cartId,
"cart",
await loaders.CustomCartLoader.loadById(cartId)
);
},
},
},
});