D-James-GH / cached_query

Simple caching for flutter apps
MIT License
47 stars 10 forks source link

Support composite query keys. #13

Closed Delgerskhn closed 8 months ago

Delgerskhn commented 1 year ago

I have just started using this package. It works great. And I noticed that the query keys are not identical to react-query. For now I am building query key strings with different ids like 'posts-$id'. And I would like to propose feature for supporting composite keys like react-query. I think this will be beneficial for searching and filtering logic. I want to have something like ` var filter = { 'query': 'food', 'page': 1, 'limit': 10, 'filters': [ { 'rating': 3.5 } ] };

var query = Query(['posts', filter], queryFn: fetchPosts); `

D-James-GH commented 1 year ago

I have thought about adding this type of key as I agree it is useful in react query. However, I also find that it adds some hidden magic and is more difficult to understand and reason about.

In react query I use the composite keys mainly for invalidating or updating a group of queries at once. In this package, Cached Query, you can achieve the same effect by passing a "filter function" parameter to the update function.

CachedQuery.instance.updateQuery(
  updateFn: (dynamic oldData){ 
    if(oldData is Todo){
      return oldData?.copyWith(complete: true);
    }
  },
  filterFn: (unencodedKey, key) => key.startsWith("todos/"),
);

This gives the flexibility of filtering queries to the user of the package. You can add your keys in any way that can be converted using jsonEncode.

For example, using your filter map as the query key, you can update only queries where page is equal to 10.

CachedQuery.instance.updateQuery(
  ...
  filterFn: (unencodedKey, key) => unencodedKey["page"] == 10,
);

Are there any other areas you use react query keys that the approach I mentioned doesn't work?