-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathcreateBaseQuery.ts
85 lines (78 loc) · 2.38 KB
/
createBaseQuery.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { derived, get, readable } from 'svelte/store'
import { notifyManager } from '@tanstack/query-core'
import { useIsRestoring } from './useIsRestoring.js'
import { useQueryClient } from './useQueryClient.js'
import { isSvelteStore, noop } from './utils.js'
import type {
QueryClient,
QueryKey,
QueryObserver,
QueryObserverResult,
} from '@tanstack/query-core'
import type {
CreateBaseQueryOptions,
CreateBaseQueryResult,
StoreOrVal,
} from './types.js'
export function createBaseQuery<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey extends QueryKey,
>(
options: StoreOrVal<
CreateBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
>,
Observer: typeof QueryObserver,
queryClient?: QueryClient,
): CreateBaseQueryResult<TData, TError> {
/** Load query client */
const client = useQueryClient(queryClient)
const isRestoring = useIsRestoring()
/** Converts options to a svelte store if not already a store object */
const optionsStore = isSvelteStore(options) ? options : readable(options)
/** Creates a store that has the default options applied */
const defaultedOptionsStore = derived(
[optionsStore, isRestoring],
([$optionsStore, $isRestoring]) => {
const defaultedOptions = client.defaultQueryOptions($optionsStore)
defaultedOptions._optimisticResults = $isRestoring
? 'isRestoring'
: 'optimistic'
return defaultedOptions
},
)
/** Creates the observer */
const observer = new Observer<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>(client, get(defaultedOptionsStore))
defaultedOptionsStore.subscribe(($defaultedOptions) => {
observer.setOptions($defaultedOptions)
})
const result = derived<
typeof isRestoring,
QueryObserverResult<TData, TError>
>(isRestoring, ($isRestoring, set) => {
const unsubscribe = $isRestoring
? noop
: observer.subscribe(notifyManager.batchCalls(set))
observer.updateResult()
return unsubscribe
})
/** Subscribe to changes in result and defaultedOptionsStore */
const { subscribe } = derived(
[result, defaultedOptionsStore],
([$result, $defaultedOptionsStore]) => {
$result = observer.getOptimisticResult($defaultedOptionsStore)
return !$defaultedOptionsStore.notifyOnChangeProps
? observer.trackResult($result)
: $result
},
)
return { subscribe }
}