Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

createBaseQuery.ts

85 lines2.4 KB

1import { derived, get, readable } from 'svelte/store'
2import { noop, notifyManager } from '@tanstack/query-core'
3import { useIsRestoring } from './useIsRestoring.js'
4import { useQueryClient } from './useQueryClient.js'
5import { isSvelteStore } from './utils.js'
6import type {
7 QueryClient,
8 QueryKey,
9 QueryObserver,
10 QueryObserverResult,
11} from '@tanstack/query-core'
12import type {
13 CreateBaseQueryOptions,
14 CreateBaseQueryResult,
15 StoreOrVal,
16} from './types.js'
17​
18export function createBaseQuery<
19 TQueryFnData,
20 TError,
21 TData,
22 TQueryData,
23 TQueryKey extends QueryKey,
24>(
25 options: StoreOrVal<
26 CreateBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
27 >,
28 Observer: typeof QueryObserver,
29 queryClient?: QueryClient,
30): CreateBaseQueryResult<TData, TError> {
31 /** Load query client */
32 const client = useQueryClient(queryClient)
33 const isRestoring = useIsRestoring()
34 /** Converts options to a svelte store if not already a store object */
35 const optionsStore = isSvelteStore(options) ? options : readable(options)
36​
37 /** Creates a store that has the default options applied */
38 const defaultedOptionsStore = derived(
39 [optionsStore, isRestoring],
40 ([$optionsStore, $isRestoring]) => {
41 const defaultedOptions = client.defaultQueryOptions($optionsStore)
42 defaultedOptions._optimisticResults = $isRestoring
43 ? 'isRestoring'
44 : 'optimistic'
45 return defaultedOptions
46 },
47 )
48​
49 /** Creates the observer */
50 const observer = new Observer<
51 TQueryFnData,
52 TError,
53 TData,
54 TQueryData,
55 TQueryKey
56 >(client, get(defaultedOptionsStore))
57​
58 defaultedOptionsStore.subscribe(($defaultedOptions) => {
59 observer.setOptions($defaultedOptions)
60 })
61​
62 const result = derived<
63 typeof isRestoring,
64 QueryObserverResult<TData, TError>
65 >(isRestoring, ($isRestoring, set) => {
66 const unsubscribe = $isRestoring
67 ? noop
68 : observer.subscribe(notifyManager.batchCalls(set))
69 observer.updateResult()
70 return unsubscribe
71 })
72​
73 /** Subscribe to changes in result and defaultedOptionsStore */
74 const { subscribe } = derived(
75 [result, defaultedOptionsStore],
76 ([$result, $defaultedOptionsStore]) => {
77 $result = observer.getOptimisticResult($defaultedOptionsStore)
78 return !$defaultedOptionsStore.notifyOnChangeProps
79 ? observer.trackResult($result)
80 : $result
81 },
82 )
83​
84 return { subscribe }