forked from TanStack/query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateBaseQuery.ts
76 lines (67 loc) · 1.96 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
import {
notifyManager,
type QueryKey,
type QueryObserver,
} from '@tanstack/query-core'
import type { CreateBaseQueryOptions, CreateBaseQueryResult } from './types'
import { useQueryClient } from './useQueryClient'
import { derived, readable } from 'svelte/store'
export function createBaseQuery<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey extends QueryKey,
>(
options: CreateBaseQueryOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>,
Observer: typeof QueryObserver,
): CreateBaseQueryResult<TData, TError> {
const queryClient = useQueryClient()
const defaultedOptions = queryClient.defaultQueryOptions(options)
defaultedOptions._optimisticResults = 'optimistic'
let observer = new Observer<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>(queryClient, defaultedOptions)
// Include callbacks in batch renders
if (defaultedOptions.onError) {
defaultedOptions.onError = notifyManager.batchCalls(
defaultedOptions.onError,
)
}
if (defaultedOptions.onSuccess) {
defaultedOptions.onSuccess = notifyManager.batchCalls(
defaultedOptions.onSuccess,
)
}
if (defaultedOptions.onSettled) {
defaultedOptions.onSettled = notifyManager.batchCalls(
defaultedOptions.onSettled,
)
}
readable(observer).subscribe(($observer) => {
observer = $observer
// Do not notify on updates because of changes in the options because
// these changes should already be reflected in the optimistic result.
observer.setOptions(defaultedOptions, { listeners: false })
})
const result = readable(observer.getCurrentResult(), (set) => {
return observer.subscribe(notifyManager.batchCalls(set))
})
const { subscribe } = derived(result, ($result) => {
$result = observer.getOptimisticResult(defaultedOptions)
return !defaultedOptions.notifyOnChangeProps
? observer.trackResult($result)
: $result
})
return { subscribe }
}