Repository navigation
Expand file tree
/
Copy pathuseBaseQuery.ts
More file actions
308 lines (282 loc) · 9.09 KB
/
Copy pathuseBaseQuery.ts
File metadata and controls
308 lines (282 loc) · 9.09 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import { shouldThrowError } from '@tanstack/query-core'
import {
computed,
getCurrentScope,
onScopeDispose,
reactive,
readonly,
shallowReactive,
shallowReadonly,
toRefs,
watch,
} from 'vue-demi'
import { useQueryClient } from './useQueryClient'
import { cloneDeepUnref, updateState } from './utils'
import type {
DefaultedQueryObserverOptions,
QueryKey,
QueryObserver,
QueryObserverResult,
} from '@tanstack/query-core'
import type { Ref } from 'vue-demi'
import type { QueryClient } from './queryClient'
import type { UseQueryOptions } from './queryOptions'
import type { MaybeRefOrGetter } from './types'
import type { UseInfiniteQueryOptions } from './useInfiniteQuery'
/**
* Readonly view of a union that stays a union. A single `Readonly<Union>` collapses the members, which
* drops the `status` / `isSuccess` / `isPending` discriminants.
*/
type ReadonlyQueryState<T> = T extends any
? { readonly [K in keyof T]: T[K] }
: never
/**
* The result of the query composables: every property of the observer result wrapped in a `Ref`, except
* the `refetch`, `fetchNextPage`, and `fetchPreviousPage` functions, plus `suspense` and `state`.
*/
export type UseBaseQueryReturnType<
TData,
TError,
TResult = QueryObserverResult<TData, TError>,
> = {
[K in keyof TResult]: K extends
| 'fetchNextPage'
| 'fetchPreviousPage'
| 'refetch'
? TResult[K]
: Ref<Readonly<TResult>[K]>
} & {
/**
* Returns a promise for use with Vue's `Suspense` or `onServerPrefetch`. It fetches the query if it has no
* data or its data is stale and resolves with the result once that fetch resolves (usually when the query
* function finishes, but earlier after the first chunk of a streamed query or when data is set during the
* fetch), or resolves immediately if the data is fresh. While the query is disabled, it waits until the query
* is enabled. If the fetch fails, it resolves with the error result, unless `throwOnError` is (or returns)
* `true`, in which case it rejects.
*/
suspense: () => Promise<TResult>
/**
* The query result as one readonly reactive object. `data`, `error`, `status`, `isPending`, and the other
* fields are plain values — read `state.data`, not `state.data.value`.
*
* The object is a discriminated union, so a check on `status`, `isSuccess`, `isPending`, or `isError`
* narrows the other fields. When `status` is `'success'` (or `isSuccess` is `true`), `data` is `TData`.
* When `status` is `'pending'` (or `isPending` is `true`), `data` is `undefined` and `error` is `null`.
* @example
* ```vue
* <script setup lang="ts">
* import { useQuery } from '@tanstack/vue-query'
*
* const { state } = useQuery({
* queryKey: ['post'],
* queryFn: fetchPost,
* })
*
* if (state.status === 'success') {
* // `state.data` is `Post`, not `Post | undefined`
* console.log(state.data.title)
* }
* </script>
*
* <template>
* <span v-if="state.status === 'pending'">Loading...</span>
* <span v-else-if="state.status === 'error'">Error: {{ state.error.message }}</span>
* <h1 v-else>{{ state.data.title }}</h1>
* </template>
* ```
*/
state: ReadonlyQueryState<TResult>
}
type UseQueryOptionsGeneric<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> =
| UseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
| UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>
/**
* Base implementation shared by `useQuery` and `useInfiniteQuery`.
* @param Observer - The observer class from query-core (`QueryObserver` or `InfiniteQueryObserver`).
* @param options - A `ref`, plain value, or reactive getter resolving to the query options.
* @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
* will be used.
* @returns The query result as `ref`s, plus the `suspense` function.
*/
export function useBaseQuery<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey extends QueryKey,
TPageParam,
>(
Observer: typeof QueryObserver,
options: MaybeRefOrGetter<
UseQueryOptionsGeneric<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey,
TPageParam
>
>,
queryClient?: QueryClient,
): UseBaseQueryReturnType<TData, TError> {
if (process.env.NODE_ENV === 'development') {
if (!getCurrentScope()) {
console.warn(
'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
)
}
}
const client = queryClient || useQueryClient()
const defaultedOptions = computed(() => {
let resolvedOptions = options
if (typeof resolvedOptions === 'function') {
resolvedOptions = resolvedOptions()
}
const clonedOptions = cloneDeepUnref(resolvedOptions as any)
// A zero-arg function is a Vue getter and must run here so its refs are tracked.
// `(query) => boolean` is query-core's callback and is left for core to call.
if (
typeof clonedOptions.enabled === 'function' &&
clonedOptions.enabled.length === 0
) {
clonedOptions.enabled = clonedOptions.enabled()
}
const defaulted: DefaultedQueryObserverOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
> = client.defaultQueryOptions(clonedOptions)
defaulted._optimisticResults = client.isRestoring?.value
? 'isRestoring'
: 'optimistic'
return defaulted
})
const observer = new Observer(client, defaultedOptions.value)
// @ts-expect-error
const state = defaultedOptions.value.shallow
? shallowReactive(observer.getCurrentResult())
: reactive(observer.getCurrentResult())
let unsubscribe = () => {
// noop
}
// Replaced below with the wrapper. Declared here so the subscriber can put it
// back after `updateState` copies the observer's own `refetch` onto `state`.
let refetch: (typeof state)['refetch'] = (...args) =>
observer.refetch(...args)
if (client.isRestoring) {
watch(
client.isRestoring,
(isRestoring) => {
if (!isRestoring) {
unsubscribe()
unsubscribe = observer.subscribe((result) => {
updateState(state, result)
state.refetch = refetch
})
}
},
{ immediate: true },
)
}
const updater = () => {
observer.setOptions(defaultedOptions.value)
updateState(state, observer.getCurrentResult())
state.refetch = refetch
}
watch(defaultedOptions, updater)
onScopeDispose(() => {
unsubscribe()
})
// fix #5910. Call `observer.refetch`: `state.refetch` is this wrapper, so
// calling it would recurse.
refetch = (...args) => {
updater()
return observer.refetch(...args)
}
state.refetch = refetch
const suspense = () => {
return new Promise<QueryObserverResult<TData, TError>>(
(resolve, reject) => {
let stopWatch = () => {
// noop
}
const run = () => {
// Apply the latest options before resolving `enabled`, so a query callback sees the current query.
// fix #6133
observer.setOptions(defaultedOptions.value)
const { enabled } = defaultedOptions.value
if (
(typeof enabled === 'function'
? enabled(observer.getCurrentQuery())
: enabled) !== false
) {
const optimisticResult = observer.getOptimisticResult(
defaultedOptions.value,
)
if (optimisticResult.isStale) {
stopWatch()
observer
.fetchOptimistic(defaultedOptions.value)
.then(resolve, (error: TError) => {
if (
shouldThrowError(defaultedOptions.value.throwOnError, [
error,
observer.getCurrentQuery(),
])
) {
reject(error)
} else {
resolve(observer.getCurrentResult())
}
})
} else {
stopWatch()
resolve(optimisticResult)
}
}
}
run()
stopWatch = watch(defaultedOptions, run)
},
)
}
// Handle error boundary
watch(
() => state.error,
(error) => {
if (
state.isError &&
!state.isFetching &&
shouldThrowError(defaultedOptions.value.throwOnError, [
error as TError,
observer.getCurrentQuery(),
])
) {
throw error
}
},
)
// @ts-expect-error
const readonlyState = defaultedOptions.value.shallow
? shallowReadonly(state)
: readonly(state)
const object: any = toRefs(readonlyState)
for (const key in state) {
if (typeof state[key as keyof typeof state] === 'function') {
object[key] = state[key as keyof typeof state]
}
}
object.suspense = suspense
object.refetch = refetch
object.state = readonlyState
return object as UseBaseQueryReturnType<TData, TError>
}