forked from TanStack/query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseBaseQuery.ts
391 lines (360 loc) · 11.2 KB
/
useBaseQuery.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// Had to disable the lint rule because isServer type is defined as false
// in solid-js/web package. I'll create a GitHub issue with them to see
// why that happens.
import { hydrate, notifyManager } from '@tanstack/query-core'
import { isServer } from 'solid-js/web'
import {
createComputed,
createMemo,
createResource,
createSignal,
on,
onCleanup,
} from 'solid-js'
import { createStore, reconcile, unwrap } from 'solid-js/store'
import { useQueryClient } from './QueryClientProvider'
import { shouldThrowError } from './utils'
import { useIsRestoring } from './isRestoring'
import type { UseBaseQueryOptions } from './types'
import type { Accessor, Signal } from 'solid-js'
import type { QueryClient } from './QueryClient'
import type {
Query,
QueryKey,
QueryObserver,
QueryObserverResult,
} from '@tanstack/query-core'
function reconcileFn<TData, TError>(
store: QueryObserverResult<TData, TError>,
result: QueryObserverResult<TData, TError>,
reconcileOption:
| string
| false
| ((oldData: TData | undefined, newData: TData) => TData),
queryHash?: string,
): QueryObserverResult<TData, TError> {
if (reconcileOption === false) return result
if (typeof reconcileOption === 'function') {
const newData = reconcileOption(store.data, result.data as TData)
return { ...result, data: newData } as typeof result
}
let data = result.data
if (store.data === undefined) {
try {
data = structuredClone(data)
} catch (error) {
if (process.env.NODE_ENV !== 'production') {
if (error instanceof Error) {
console.warn(
`Unable to correctly reconcile data for query key: ${queryHash}. ` +
`Possibly because the query data contains data structures that aren't supported ` +
`by the 'structuredClone' algorithm. Consider using a callback function instead ` +
`to manage the reconciliation manually.\n\n Error Received: ${error.name} - ${error.message}`,
)
}
}
}
}
const newData = reconcile(data, { key: reconcileOption })(store.data)
return { ...result, data: newData } as typeof result
}
/**
* Solid's `onHydrated` functionality will silently "fail" (hydrate with an empty object)
* if the resource data is not serializable.
*/
const hydratableObserverResult = <
TQueryFnData,
TError,
TData,
TQueryKey extends QueryKey,
TDataHydratable,
>(
query: Query<TQueryFnData, TError, TData, TQueryKey>,
result: QueryObserverResult<TDataHydratable, TError>,
) => {
if (!isServer) return result
const obj: any = {
...unwrap(result),
// During SSR, functions cannot be serialized, so we need to remove them
// This is safe because we will add these functions back when the query is hydrated
refetch: undefined,
}
// If the query is an infinite query, we need to remove additional properties
if ('fetchNextPage' in result) {
obj.fetchNextPage = undefined
obj.fetchPreviousPage = undefined
}
// We will also attach the dehydrated state of the query to the result
// This will be removed on client after hydration
obj.hydrationData = {
state: query.state,
queryKey: query.queryKey,
queryHash: query.queryHash,
...(query.meta && { meta: query.meta }),
}
return obj
}
// Base Query Function that is used to create the query.
export function useBaseQuery<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey extends QueryKey,
>(
options: Accessor<
UseBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
>,
Observer: typeof QueryObserver,
queryClient?: Accessor<QueryClient>,
) {
type ResourceData = QueryObserverResult<TData, TError>
const client = createMemo(
() => useQueryClient(queryClient?.()),
useQueryClient(queryClient?.()),
)
const isRestoring = useIsRestoring()
// There are times when we run a query on the server but the resource is never read
// This could lead to times when the queryObserver is unsubscribed before the resource has loaded
// Causing a time out error. To prevent this we will queue the unsubscribe if the cleanup is called
// before the resource has loaded
let unsubscribeQueued = false
const defaultedOptions = createMemo(() => {
const defaultOptions = client().defaultQueryOptions(options())
defaultOptions._optimisticResults = isRestoring()
? 'isRestoring'
: 'optimistic'
defaultOptions.structuralSharing = false
if (isServer) {
defaultOptions.retry = false
defaultOptions.throwOnError = true
}
return defaultOptions
})
const initialOptions = defaultedOptions()
const [observer, setObserver] = createSignal(
new Observer(client(), defaultedOptions()),
)
let observerResult = observer().getOptimisticResult(defaultedOptions())
const [state, setState] =
createStore<QueryObserverResult<TData, TError>>(observerResult)
const createServerSubscriber = (
resolve: (
data: ResourceData | PromiseLike<ResourceData | undefined> | undefined,
) => void,
reject: (reason?: any) => void,
) => {
return observer().subscribe((result) => {
notifyManager.batchCalls(() => {
const query = observer().getCurrentQuery()
const unwrappedResult = hydratableObserverResult(query, result)
if (unwrappedResult.isError) {
reject(unwrappedResult.error)
unsubscribeIfQueued()
} else {
resolve(unwrappedResult)
unsubscribeIfQueued()
}
})()
})
}
const unsubscribeIfQueued = () => {
if (unsubscribeQueued) {
unsubscribe?.()
unsubscribeQueued = false
}
}
const createClientSubscriber = () => {
const obs = observer()
return obs.subscribe((result) => {
observerResult = result
queueMicrotask(() => {
if (unsubscribe) {
refetch()
}
})
})
}
function setStateWithReconciliation(res: typeof observerResult) {
const opts = observer().options
// @ts-expect-error - Reconcile option is not correctly typed internally
const reconcileOptions = opts.reconcile
setState((store) => {
return reconcileFn(
store,
res,
reconcileOptions === undefined ? false : reconcileOptions,
opts.queryHash,
)
})
}
function createDeepSignal<T>(): Signal<T> {
return [
() => state,
(v: any) => {
const unwrapped = unwrap(state)
if (typeof v === 'function') {
v = v(unwrapped)
}
// Hydration data exists on first load after SSR,
// and should be removed from the observer result
if (v?.hydrationData) {
const { hydrationData, ...rest } = v
v = rest
}
setStateWithReconciliation(v)
},
] as Signal<T>
}
/**
* Unsubscribe is set lazily, so that we can subscribe after hydration when needed.
*/
let unsubscribe: (() => void) | null = null
/*
Fixes #7275
In a few cases, the observer could unmount before the resource is loaded.
This leads to Suspense boundaries to be suspended indefinitely.
This resolver will be called when the observer is unmounting
but the resource is still in a loading state
*/
let resolver: ((value: ResourceData) => void) | null = null
const [queryResource, { refetch }] = createResource<ResourceData | undefined>(
() => {
const obs = observer()
return new Promise((resolve, reject) => {
resolver = resolve
if (isServer) {
unsubscribe = createServerSubscriber(resolve, reject)
} else if (!unsubscribe && !isRestoring()) {
unsubscribe = createClientSubscriber()
}
obs.updateResult()
if (
observerResult.isError &&
!observerResult.isFetching &&
!isRestoring() &&
shouldThrowError(obs.options.throwOnError, [
observerResult.error,
obs.getCurrentQuery(),
])
) {
setStateWithReconciliation(observerResult)
return reject(observerResult.error)
}
if (!observerResult.isLoading) {
resolver = null
return resolve(
hydratableObserverResult(obs.getCurrentQuery(), observerResult),
)
}
setStateWithReconciliation(observerResult)
})
},
{
storage: createDeepSignal,
get deferStream() {
return options().deferStream
},
/**
* If this resource was populated on the server (either sync render, or streamed in over time), onHydrated
* will be called. This is the point at which we can hydrate the query cache state, and setup the query subscriber.
*
* Leveraging onHydrated allows us to plug into the async and streaming support that solidjs resources already support.
*
* Note that this is only invoked on the client, for queries that were originally run on the server.
*/
onHydrated(_k, info) {
if (info.value && 'hydrationData' in info.value) {
hydrate(client(), {
// @ts-expect-error - hydrationData is not correctly typed internally
queries: [{ ...info.value.hydrationData }],
})
}
if (unsubscribe) return
/**
* Do not refetch query on mount if query was fetched on server,
* even if `staleTime` is not set.
*/
const newOptions = { ...initialOptions }
if (
(initialOptions.staleTime || !initialOptions.initialData) &&
info.value
) {
newOptions.refetchOnMount = false
}
// Setting the options as an immutable object to prevent
// wonky behavior with observer subscriptions
observer().setOptions(newOptions)
setStateWithReconciliation(observer().getOptimisticResult(newOptions))
unsubscribe = createClientSubscriber()
},
},
)
createComputed(
on(
client,
(c) => {
if (unsubscribe) {
unsubscribe()
}
const newObserver = new Observer(c, defaultedOptions())
unsubscribe = createClientSubscriber()
setObserver(newObserver)
},
{
defer: true,
},
),
)
createComputed(
on(
isRestoring,
(restoring) => {
if (!restoring && !isServer) {
refetch()
}
},
{ defer: true },
),
)
onCleanup(() => {
if (isServer && queryResource.loading) {
unsubscribeQueued = true
return
}
if (unsubscribe) {
unsubscribe()
unsubscribe = null
}
if (resolver && !isServer) {
resolver(observerResult)
resolver = null
}
})
createComputed(
on(
[observer, defaultedOptions],
([obs, opts]) => {
obs.setOptions(opts)
setStateWithReconciliation(obs.getOptimisticResult(opts))
refetch()
},
{ defer: true },
),
)
const handler = {
get(
target: QueryObserverResult<TData, TError>,
prop: keyof QueryObserverResult<TData, TError>,
): any {
if (prop === 'data') {
if (state.data !== undefined) {
return queryResource.latest?.data
}
return queryResource()?.data
}
return Reflect.get(target, prop)
},
}
return new Proxy(state, handler)
}