|
1
|
import { QueryKey, UseQueryOptions } from "@tanstack/react-query" |
|
2
|
|
|
3
|
export type TQueryKey<TKey, TListQuery = any, TDetailQuery = string> = { |
|
4
|
all: readonly [TKey] |
|
5
|
lists: () => readonly [...TQueryKey<TKey>["all"], "list"] |
|
6
|
list: ( |
|
7
|
query?: TListQuery |
|
8
|
) => readonly [...ReturnType<TQueryKey<TKey>["lists"]>, { query: TListQuery }] |
|
9
|
details: () => readonly [...TQueryKey<TKey>["all"], "detail"] |
|
10
|
detail: ( |
|
11
|
id: TDetailQuery, |
|
12
|
query?: TListQuery |
|
13
|
) => readonly [ |
|
14
|
...ReturnType<TQueryKey<TKey>["details"]>, |
|
15
|
TDetailQuery, |
|
16
|
{ query: TListQuery } |
|
17
|
] |
|
18
|
} |
|
19
|
|
|
20
|
export type UseQueryOptionsWrapper< |
|
21
|
// Return type of queryFn |
|
22
|
TQueryFn = unknown, |
|
23
|
// Type thrown in case the queryFn rejects |
|
24
|
E = Error, |
|
25
|
// Query key type |
|
26
|
TQueryKey extends QueryKey = QueryKey |
|
27
|
> = Omit< |
|
28
|
UseQueryOptions<TQueryFn, E, TQueryFn, TQueryKey>, |
|
29
|
"queryKey" | "queryFn" |
|
30
|
> |
|
31
|
|
|
32
|
export const queryKeysFactory = < |
|
33
|
T, |
|
34
|
TListQueryType = any, |
|
35
|
TDetailQueryType = string |
|
36
|
>( |
|
37
|
globalKey: T |
|
38
|
) => { |
|
39
|
const queryKeyFactory: TQueryKey<T, TListQueryType, TDetailQueryType> = { |
|
40
|
all: [globalKey], |
|
41
|
lists: () => [...queryKeyFactory.all, "list"], |
|
42
|
list: (query?: TListQueryType) => |
|
43
|
[...queryKeyFactory.lists(), query ? { query } : undefined].filter( |
|
44
|
(k) => !!k |
|
45
|
) as unknown as readonly [T, "list", { query: TListQueryType }], |
|
46
|
details: () => [...queryKeyFactory.all, "detail"], |
|
47
|
detail: (id: TDetailQueryType, query?: TListQueryType) => |
|
48
|
[...queryKeyFactory.details(), id, query ? { query } : undefined].filter( |
|
49
|
(k) => !!k |
|
50
|
) as unknown as readonly [ |
|
51
|
T, |
|
52
|
"detail", |
|
53
|
TDetailQueryType, |
|
54
|
{ query: TListQueryType } |
|
55
|
], |
|
56
|
} |
|
57
|
return queryKeyFactory |
|
58
|
} |