Hi,
In my current project, I want to loop through the ApolloClient cache in order to list the key and pick the ones I want to clear for specific clients.
I am using lodash’s forEach
function and doing the following
forEach(client.cache.data.data, (entry, key) => {
});
Is this the best approach? Probably not, but I couldn’t find any documentation that explains how I could achieve this the best way possible.
The reason behind this is because on my GraphQL server, I am sending to the client the _id of all the data that is being cleared and need to be evicted from the connected clients.
Since the id
looks like TypeName:ID
, I wanted to loop through the cache and remove all entries that match the _id
in the keys instead of having to return the TypeName:ID
.
Hope you can point me in the right direction, thanks!
Hi @Kheang_Hok_Chin
thanks for posting! I haven’t seen this approach before. Can you describe a bit more about your use case? A few questions come to mind:
- What does the server know that makes it the source of truth for client-side cache invalidation?
- What sort of performance or scale issues have you been seeing?
- How large do your client-side caches get?
Thanks for your comment.
I use mongodb for a datasource in my GraphQL server and cache some of the queries.
I clear them when a mutation occurs.
On the client side, I need to be able to know what to clear from the cache when that happens.
At first I thought that I could simply use cache.evict({ id: "" })
to clear a specific result and use cache.gc()
but it didn’t seem to produce the result I needed.
So instead I followed this approach here that I mentioned that also allows me to scale.
On the client side, I listen on a socket connection for a list of queries to clear when a mutation is executed on GraphQL’s side.
// loop through queries and clear the cache for each
forEach(get(cacheEvict, "queries"), fieldName => {
client.cache.evict({ id: "ROOT_QUERY", fieldName });
});
This is less specific than I want it to be but it works for my use case until I find an even more precise solution that would work better. Since I had no examples to rely upon for complex scenarios, this is the one I came up with.