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

createBaseQuery.ts

87 lines2.5 KB

1import { derived, get, readable } from 'svelte/store'
2import { notifyManager } from '@tanstack/query-core'
3import { useIsRestoring } from './useIsRestoring'
4import { useQueryClient } from './useQueryClient'
5import { isSvelteStore } from './utils'
6import type {
7 QueryClient,
8 QueryKey,
9 QueryObserver,
10 QueryObserverResult,
11} from '@tanstack/query-core'
12import type { CreateBaseQueryOptions, CreateBaseQueryResult } from './types'
13​
14export function createBaseQuery<
15 TQueryFnData,
16 TError,
17 TData,
18 TQueryData,
19 TQueryKey extends QueryKey,
20>(
21 options: CreateBaseQueryOptions<
22 TQueryFnData,
23 TError,
24 TData,
25 TQueryData,
26 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 // Do not notify on updates because of changes in the options because
60 // these changes should already be reflected in the optimistic result.
61 observer.setOptions($defaultedOptions, { listeners: false })
62 })
63​
64 const result = derived<
65 typeof isRestoring,
66 QueryObserverResult<TData, TError>
67 >(isRestoring, ($isRestoring, set) => {
68 const unsubscribe = $isRestoring
69 ? () => undefined
70 : observer.subscribe(notifyManager.batchCalls(set))
71 observer.updateResult()
72 return unsubscribe
73 })
74​
75 /** Subscribe to changes in result and defaultedOptionsStore */
76 const { subscribe } = derived(
77 [result, defaultedOptionsStore],
78 ([$result, $defaultedOptionsStore]) => {
79 $result = observer.getOptimisticResult($defaultedOptionsStore)
80 return !$defaultedOptionsStore.notifyOnChangeProps
81 ? observer.trackResult($result)
82 : $result
83 },
84 )
85​
86 return { subscribe }