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

createBaseQuery.ts

69 lines2.1 KB

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