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

createBaseQuery.ts

387 lines11.1 KB

1// Had to disable the lint rule because isServer type is defined as false
2// in solid-js/web package. I'll create a GitHub issue with them to see
3// why that happens.
4import { hydrate, notifyManager } from '@tanstack/query-core'
5import { isServer } from 'solid-js/web'
6import {
7 createComputed,
8 createMemo,
9 createResource,
10 createSignal,
11 on,
12 onCleanup,
13} from 'solid-js'
14import { createStore, reconcile, unwrap } from 'solid-js/store'
15import { useQueryClient } from './QueryClientProvider'
16import { shouldThrowError } from './utils'
17import { useIsRestoring } from './isRestoring'
18import type { CreateBaseQueryOptions } from './types'
19import type { Accessor, Signal } from 'solid-js'
20import type { QueryClient } from './QueryClient'
21import type {
22 Query,
23 QueryKey,
24 QueryObserver,
25 QueryObserverResult,
26} from '@tanstack/query-core'
27​
28function reconcileFn<TData, TError>(
29 store: QueryObserverResult<TData, TError>,
30 result: QueryObserverResult<TData, TError>,
31 reconcileOption:
32 | string
33 | false
34 | ((oldData: TData | undefined, newData: TData) => TData),
35 queryHash?: string,
36): QueryObserverResult<TData, TError> {
37 if (reconcileOption === false) return result
38 if (typeof reconcileOption === 'function') {
39 const newData = reconcileOption(store.data, result.data as TData)
40 return { ...result, data: newData } as typeof result
41 }
42 let data = result.data
43 if (store.data === undefined) {
44 try {
45 data = structuredClone(data)
46 } catch (error) {
47 if (process.env.NODE_ENV !== 'production') {
48 if (error instanceof Error) {
49 console.warn(
50 `Unable to correctly reconcile data for query key: ${queryHash}. ` +
51 `Possibly because the query data contains data structures that aren't supported ` +
52 `by the 'structuredClone' algorithm. Consider using a callback function instead ` +
53 `to manage the reconciliation manually.\n\n Error Received: ${error.name} - ${error.message}`,
54 )
55 }
56 }
57 }
58 }
59 const newData = reconcile(data, { key: reconcileOption })(store.data)
60 return { ...result, data: newData } as typeof result
62​
63/**
64 * Solid's `onHydrated` functionality will silently "fail" (hydrate with an empty object)
65 * if the resource data is not serializable.
66 */
67const hydratableObserverResult = <
68 TQueryFnData,
69 TError,
70 TData,
71 TQueryKey extends QueryKey,
72 TDataHydratable,
73>(
74 query: Query<TQueryFnData, TError, TData, TQueryKey>,
75 result: QueryObserverResult<TDataHydratable, TError>,
76) => {
77 if (!isServer) return result
78 const obj: any = {
79 ...unwrap(result),
80 // During SSR, functions cannot be serialized, so we need to remove them
81 // This is safe because we will add these functions back when the query is hydrated
82 refetch: undefined,
83 }
84​
85 // If the query is an infinite query, we need to remove additional properties
86 if ('fetchNextPage' in result) {
87 obj.fetchNextPage = undefined
88 obj.fetchPreviousPage = undefined
89 }
90​
91 // We will also attach the dehydrated state of the query to the result
92 // This will be removed on client after hydration
93 obj.hydrationData = {
94 state: query.state,
95 queryKey: query.queryKey,
96 queryHash: query.queryHash,
97 ...(query.meta && { meta: query.meta }),
98 }
99​
100 return obj
102​
103// Base Query Function that is used to create the query.
104export function createBaseQuery<
105 TQueryFnData,
106 TError,
107 TData,
108 TQueryData,
109 TQueryKey extends QueryKey,
110>(
111 options: Accessor<
112 CreateBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
113 >,
114 Observer: typeof QueryObserver,
115 queryClient?: Accessor<QueryClient>,
116) {
117 type ResourceData = QueryObserverResult<TData, TError>
118​
119 const client = createMemo(() => useQueryClient(queryClient?.()))
120 const isRestoring = useIsRestoring()
121 // There are times when we run a query on the server but the resource is never read
122 // This could lead to times when the queryObserver is unsubscribed before the resource has loaded
123 // Causing a time out error. To prevent this we will queue the unsubscribe if the cleanup is called
124 // before the resource has loaded
125 let unsubscribeQueued = false
126​
127 const defaultedOptions = createMemo(() => {
128 const defaultOptions = client().defaultQueryOptions(options())
129 defaultOptions._optimisticResults = isRestoring()
130 ? 'isRestoring'
131 : 'optimistic'
132 defaultOptions.structuralSharing = false
133 if (isServer) {
134 defaultOptions.retry = false
135 defaultOptions.throwOnError = true
136 }
137 return defaultOptions
138 })
139 const initialOptions = defaultedOptions()
140​
141 const [observer, setObserver] = createSignal(
142 new Observer(client(), defaultedOptions()),
143 )
144​
145 let observerResult = observer().getOptimisticResult(defaultedOptions())
146 const [state, setState] =
147 createStore<QueryObserverResult<TData, TError>>(observerResult)
148​
149 const createServerSubscriber = (
150 resolve: (
151 data: ResourceData | PromiseLike<ResourceData | undefined> | undefined,
152 ) => void,
153 reject: (reason?: any) => void,
154 ) => {
155 return observer().subscribe((result) => {
156 notifyManager.batchCalls(() => {
157 const query = observer().getCurrentQuery()
158 const unwrappedResult = hydratableObserverResult(query, result)
159​
160 if (unwrappedResult.isError) {
161 reject(unwrappedResult.error)
162 unsubscribeIfQueued()
163 } else {
164 resolve(unwrappedResult)
165 unsubscribeIfQueued()
166 }
167 })()
168 })
169 }
170​
171 const unsubscribeIfQueued = () => {
172 if (unsubscribeQueued) {
173 unsubscribe?.()
174 unsubscribeQueued = false
175 }
176 }
177​
178 const createClientSubscriber = () => {
179 const obs = observer()
180 return obs.subscribe((result) => {
181 observerResult = result
182 queueMicrotask(() => {
183 if (unsubscribe) {
184 refetch()
185 }
186 })
187 })
188 }
189​
190 function setStateWithReconciliation(res: typeof observerResult) {
191 const opts = observer().options
192 // @ts-expect-error - Reconcile option is not correctly typed internally
193 const reconcileOptions = opts.reconcile
194​
195 setState((store) => {
196 return reconcileFn(
197 store,
198 res,
199 reconcileOptions === undefined ? false : reconcileOptions,
200 opts.queryHash,
201 )
202 })
203 }
204​
205 function createDeepSignal<T>(): Signal<T> {
206 return [
207 () => state,
208 (v: any) => {
209 const unwrapped = unwrap(state)
210 if (typeof v === 'function') {
211 v = v(unwrapped)
212 }
213 // Hydration data exists on first load after SSR,
214 // and should be removed from the observer result
215 if (v?.hydrationData) {
216 const { hydrationData, ...rest } = v
217 v = rest
218 }
219 setStateWithReconciliation(v)
220 },
221 ] as Signal<T>
222 }
223​
224 /**
225 * Unsubscribe is set lazily, so that we can subscribe after hydration when needed.
226 */
227 let unsubscribe: (() => void) | null = null
228​
229 /*
230 Fixes #7275
231 In a few cases, the observer could unmount before the resource is loaded.
232 This leads to Suspense boundaries to be suspended indefinitely.
233 This resolver will be called when the observer is unmounting
234 but the resource is still in a loading state
235 */
236 let resolver: ((value: ResourceData) => void) | null = null
237 const [queryResource, { refetch }] = createResource<ResourceData | undefined>(
238 () => {
239 const obs = observer()
240 return new Promise((resolve, reject) => {
241 resolver = resolve
242 if (isServer) {
243 unsubscribe = createServerSubscriber(resolve, reject)
244 } else if (!unsubscribe && !isRestoring()) {
245 unsubscribe = createClientSubscriber()
246 }
247 obs.updateResult()
248​
249 if (
250 observerResult.isError &&
251 !observerResult.isFetching &&
252 !isRestoring() &&
253 shouldThrowError(obs.options.throwOnError, [
254 observerResult.error,
255 obs.getCurrentQuery(),
256 ])
257 ) {
258 setStateWithReconciliation(observerResult)
259 return reject(observerResult.error)
260 }
261 if (!observerResult.isLoading) {
262 resolver = null
263 return resolve(
264 hydratableObserverResult(obs.getCurrentQuery(), observerResult),
265 )
266 }
267​
268 setStateWithReconciliation(observerResult)
269 })
270 },
271 {
272 storage: createDeepSignal,
273​
274 get deferStream() {
275 return options().deferStream
276 },
277​
278 /**
279 * If this resource was populated on the server (either sync render, or streamed in over time), onHydrated
280 * will be called. This is the point at which we can hydrate the query cache state, and setup the query subscriber.
281 *
282 * Leveraging onHydrated allows us to plug into the async and streaming support that solidjs resources already support.
283 *
284 * Note that this is only invoked on the client, for queries that were originally run on the server.
285 */
286 onHydrated(_k, info) {
287 if (info.value && 'hydrationData' in info.value) {
288 hydrate(client(), {
289 // @ts-expect-error - hydrationData is not correctly typed internally
290 queries: [{ ...info.value.hydrationData }],
291 })
292 }
293​
294 if (unsubscribe) return
295 /**
296 * Do not refetch query on mount if query was fetched on server,
297 * even if `staleTime` is not set.
298 */
299 const newOptions = { ...initialOptions }
300 if (
301 (initialOptions.staleTime || !initialOptions.initialData) &&
302 info.value
303 ) {
304 newOptions.refetchOnMount = false
305 }
306 // Setting the options as an immutable object to prevent
307 // wonky behavior with observer subscriptions
308 observer().setOptions(newOptions)
309 setStateWithReconciliation(observer().getOptimisticResult(newOptions))
310 unsubscribe = createClientSubscriber()
311 },
312 },
313 )
314​
315 createComputed(
316 on(
317 client,
318 (c) => {
319 if (unsubscribe) {
320 unsubscribe()
321 }
322 const newObserver = new Observer(c, defaultedOptions())
323 unsubscribe = createClientSubscriber()
324 setObserver(newObserver)
325 },
326 {
327 defer: true,
328 },
329 ),
330 )
331​
332 createComputed(
333 on(
334 isRestoring,
335 (restoring) => {
336 if (!restoring && !isServer) {
337 refetch()
338 }
339 },
340 { defer: true },
341 ),
342 )
343​
344 onCleanup(() => {
345 if (isServer && queryResource.loading) {
346 unsubscribeQueued = true
347 return
348 }
349 if (unsubscribe) {
350 unsubscribe()
351 unsubscribe = null
352 }
353 if (resolver && !isServer) {
354 resolver(observerResult)
355 resolver = null
356 }
357 })
358​
359 createComputed(
360 on(
361 [observer, defaultedOptions],
362 ([obs, opts]) => {
363 obs.setOptions(opts)
364 setStateWithReconciliation(obs.getOptimisticResult(opts))
365 refetch()
366 },
367 { defer: true },
368 ),
369 )
370​
371 const handler = {
372 get(
373 target: QueryObserverResult<TData, TError>,
374 prop: keyof QueryObserverResult<TData, TError>,
375 ): any {
376 if (prop === 'data') {
377 if (state.data !== undefined) {
378 return queryResource.latest?.data
379 }
380 return queryResource()?.data
381 }
382 return Reflect.get(target, prop)
383 },
384 }
385​
386 return new Proxy(state, handler)