lukemorales / query-key-factory

A library for creating typesafe standardized query keys, useful for cache management in @tanstack/query
https://www.npmjs.com/package/@lukemorales/query-key-factory
MIT License
1.21k stars 32 forks source link

Support for more nesting #81

Closed SangJunBak closed 10 months ago

SangJunBak commented 10 months ago

It seems like the current API exposes only three levels of nesting (the definition for createQueryKeys, the sub-queries defined in createQueryKeys's schema, and the contextQueries property).

Assuming I want to generate the following nested query key structure:

region('region'): {
  todos('region', 'todos'): {
    detail('region', 'todos', 'detail'): (id) => {
      queryKey: ('region', 'todos', 'detail', id)
    },
    list('region', 'todos', 'list'): (filters) => {
      queryKey: ('region', 'todos', 'list', filters),
      search: (limit) => {
        queryKey: ('region', 'todos', 'list', filters, limit)
      }
    }
  },
  users('regions', 'users'): {
    ...
  }
}

And I want to compose todos and users using createQueryKey. Is it possible to do something like:

todos = createQueryKeys('todos', ...)
users = createQueryKeys('users', ...)

region = createQueryKeys('regions', 
  contextQueries: mergeQueryKeys(todos, users)
);

?

Ideally I want the API when getting the keys to look like:

useQuery(region.list(filters).search(limit)) // ['region', 'list', filters, 'search', limit]
lukemorales commented 10 months ago

Hi @SangJunBak, from what I can see this should be already possible with the current API:

const keys = createQueryKeys('region', {
  todos: {
    queryKey: null,
    contextQueries: {
      detail: (id) => ({
        queryKey: [id],
        {...}
      }),
      list: (filters) => {...}
    }
  }, 
}

LMK if I'm missing something

SangJunBak commented 10 months ago

Ah I didn't realize you can next context queries within context queries. Thanks for the help!