-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.ts
62 lines (54 loc) · 1.94 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import type { QueryKey } from '@tanstack/react-query';
import type { InfiniteQueryOptions, QueryOptions } from './type';
interface MakeQueryOptions<Keys extends QueryKey, Args extends QueryKey, Data> {
keys: Keys;
fetcher: (...args: Args) => (Data | Promise<Data>);
}
export function createQuery<
Data = unknown,
Args extends QueryKey = QueryKey,
Keys extends QueryKey = QueryKey,
>(options: MakeQueryOptions<Keys, Args, Data>) {
const { keys: baseKeys, fetcher } = options;
const getKey = () => baseKeys;
const getKeys = (...args: Args): [...Keys, ...Args] => [...getKey(), ...args];
return Object.assign(fetcher, {
getKey,
getKeys,
getQueryOptions(...args: Args): QueryOptions<Data, unknown, ReturnType<typeof getKeys>> {
return {
queryKey: getKeys(...args),
queryFn: () => fetcher(...args),
};
},
});
}
interface MakeInfiniteQueryOptions<Keys extends QueryKey, PageParam, Args extends QueryKey, Data> {
keys: Keys;
fetcher: (pageParam: PageParam, ...args: Args) => (Data | Promise<Data>);
initialPageParam: PageParam;
getNextPageParam: InfiniteQueryOptions<Data, unknown, PageParam, Keys>['getNextPageParam'];
}
export function createInfiniteQuery<
Data = unknown,
PageParam = unknown,
Args extends QueryKey = QueryKey,
Keys extends QueryKey = QueryKey,
>(options: MakeInfiniteQueryOptions<Keys, PageParam, Args, Data>) {
const { keys: baseKeys, fetcher, initialPageParam, getNextPageParam } = options;
const getKey = () => baseKeys;
const getKeys = (...args: Args): [...Keys, ...Args] => [...getKey(), ...args];
type IKeys = ReturnType<typeof getKeys>;
return Object.assign(fetcher, {
getKey,
getKeys,
getQueryOptions(...args: Args): InfiniteQueryOptions<Data, unknown, PageParam, IKeys> {
return {
queryKey: getKeys(...args),
queryFn: (ctx) => fetcher(ctx.pageParam, ...args),
initialPageParam,
getNextPageParam,
};
},
});
}