logaretm / villus

🏎 A tiny and fast GraphQL client for Vue.js
https://villus.dev
MIT License
790 stars 31 forks source link

feat: cache eviction mechanism #184

Closed logaretm closed 1 year ago

logaretm commented 1 year ago

What

This PR aims to introduce a way to clear the cache and overall improve the caching mechanism offered by villus.

There have been several suggestions, and the following needs to be implemented

How

This suggestion has been the best so far as it doesn't include any guessing or being too clever about this. Queries can have "tags" and mutations could also clear those cached query tags.

This probably will have a lot of changes internally however it will be invisible to the end user so it is a great opportunity to try out.

closes #147 and #84

codecov-commenter commented 1 year ago

Codecov Report

Merging #184 (48ee95e) into main (97cb093) will increase coverage by 0.01%. The diff coverage is 95.16%.

@@            Coverage Diff             @@
##             main     #184      +/-   ##
==========================================
+ Coverage   94.10%   94.11%   +0.01%     
==========================================
  Files          21       21              
  Lines         492      544      +52     
  Branches      109      122      +13     
==========================================
+ Hits          463      512      +49     
- Misses         29       32       +3     
Impacted Files Coverage Δ
packages/villus/src/cache.ts 94.87% <93.10%> (-5.13%) :arrow_down:
packages/villus/src/client.ts 96.80% <94.11%> (-0.66%) :arrow_down:
packages/villus/src/useMutation.ts 96.55% <100.00%> (+0.55%) :arrow_up:
packages/villus/src/useQuery.ts 97.59% <100.00%> (+0.18%) :arrow_up:
packages/villus/src/utils/common.ts 100.00% <100.00%> (ø)

:mega: We’re building smart automated test selection to slash your CI/CD build times. Learn more

fanckush commented 1 year ago

this is awesome, refetchTags is really useful. It's the perfect balance of manual work and minimal magic. That said, would there be a way to extend this to support something along the lines of:

given the following query:

const { data } = useQuery(GetPosts, {
   tags: ['all_posts'],
 });

i'd like to utilize the tags to somehow update the cache either something like:

const { execute } = useMutation(CreatePost, {
  updateCacheTags: {
    'all_posts': (taggedQueries: Query[]) => {
        taggedQueries(cachedQuery => {
          // ... some code to update the cache of the query
          cachedQuery.push(...)
        })
    }),
});

or

const { execute } = useMutation(CreatePost);
await execute()
const allPostsCache = useCached('all_posts')
// ... some code to update the cache of the queries with `all_posts` tag

I can totally see this being outside the scope of villus 👍

logaretm commented 1 year ago

At the moment seems out of scope, but I do see the benefit of it for optimistic updates. Maybe in the future. Thanks for the suggestion.