Open History to see the last commit
1/* eslint-disable @typescript-eslint/no-unnecessary-condition */
2// Had to disable the lint rule because isServer type is defined as false
3// in solid-js/web package. I'll create a GitHub issue with them to see
4// why that happens.
5import type {
6 QueryKey,
7 QueryObserver,
8 QueryObserverResult,
9} from '@tanstack/query-core'
10import type { QueryClient } from './QueryClient'
11import { hydrate, notifyManager } from '@tanstack/query-core'
12import type { Accessor } from 'solid-js'
13import { isServer } from 'solid-js/web'
14import {
15 createComputed,
16 createMemo,
17 createResource,
18 on,
19 onCleanup,
20} from 'solid-js'
21import { createStore, reconcile, unwrap } from 'solid-js/store'
22import { useQueryClient } from './QueryClientProvider'
23import type { CreateBaseQueryOptions } from './types'
24import { shouldThrowError } from './utils'
25β
26function reconcileFn<TData, TError>(
27 store: QueryObserverResult<TData, TError>,
28 result: QueryObserverResult<TData, TError>,
29 reconcileOption:
30 | string
31 | false
32 | ((oldData: TData | undefined, newData: TData) => TData),
33): QueryObserverResult<TData, TError> {
34 if (reconcileOption === false) return result
35 if (typeof reconcileOption === 'function') {
36 const newData = reconcileOption(store.data, result.data as TData)
37 return { ...result, data: newData } as typeof result
38 }
39 const newData = reconcile(result.data, { key: reconcileOption })(store.data)
40 return { ...result, data: newData } as typeof result
41}
42β
43// Base Query Function that is used to create the query.
44export function createBaseQuery<
45 TQueryFnData,
46 TError,
47 TData,
48 TQueryData,
49 TQueryKey extends QueryKey,
50>(
51 options: Accessor<
52 CreateBaseQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
53 >,
54 Observer: typeof QueryObserver,
55 queryClient?: Accessor<QueryClient>,
56) {
57 const client = createMemo(() => useQueryClient(queryClient?.()))
58β
59 const defaultedOptions = client().defaultQueryOptions(options())
60 defaultedOptions._optimisticResults = 'optimistic'
61 defaultedOptions.structuralSharing = false
62 if (isServer) {
63 defaultedOptions.retry = false
64 defaultedOptions.throwOnError = true
65 }
66 const observer = new Observer(client(), defaultedOptions)
67β
68 const [state, setState] = createStore<QueryObserverResult<TData, TError>>(
69 observer.getOptimisticResult(defaultedOptions),
70 )
71β
72 const createServerSubscriber = (
73 resolve: (
74 data:
75 | QueryObserverResult<TData, TError>
76 | PromiseLike<QueryObserverResult<TData, TError> | undefined>
77 | undefined,
78 ) => void,
79 reject: (reason?: any) => void,
80 ) => {
81 return observer.subscribe((result) => {
82 notifyManager.batchCalls(() => {
83 const query = observer.getCurrentQuery()
84 const { refetch, ...rest } = unwrap(result)
85 const unwrappedResult = {
86 ...rest,
87β
88 // hydrate() expects a QueryState object, which is similar but not
89 // quite the same as a QueryObserverResult object. Thus, for now, we're
90 // copying over the missing properties from state in order to support hydration
91 dataUpdateCount: query.state.dataUpdateCount,
92 fetchFailureCount: query.state.fetchFailureCount,
93 // Removing these properties since they might not be serializable
94 // fetchFailureReason: query.state.fetchFailureReason,
95 // fetchMeta: query.state.fetchMeta,
96 isInvalidated: query.state.isInvalidated,
97 }
98β
99 if (unwrappedResult.isError) {
100 if (process.env['NODE_ENV'] === 'development') {
101 console.error(unwrappedResult.error)
102 }
103 reject(unwrappedResult.error)
104 }
105 if (unwrappedResult.isSuccess) {
106 // Use of any here is fine
107 // We cannot include refetch since it is not serializable
108 resolve(unwrappedResult as any)
109 }
110 })()
111 })
112 }
113β
114 const createClientSubscriber = () => {
115 return observer.subscribe((result) => {
116 notifyManager.batchCalls(() => {
117 // @ts-expect-error - This will error because the reconcile option does not
118 // exist on the query-core QueryObserverResult type
119 const reconcileOptions = observer.options.reconcile
120 // If the query has data we dont suspend but instead mutate the resource
121 // This could happen when placeholderData/initialData is defined
122 if (queryResource()?.data && result.data && !queryResource.loading) {
123 setState((store) => {
124 return reconcileFn(
125 store,
126 result,
127 reconcileOptions === undefined ? 'id' : reconcileOptions,
128 )
129 })
130 mutate(state)
131 } else {
132 setState((store) => {
133 return reconcileFn(
134 store,
135 result,
136 reconcileOptions === undefined ? 'id' : reconcileOptions,
137 )
138 })
139 refetch()
140 }
141 })()
142 })
143 }
144β
145 /**
146 * Unsubscribe is set lazily, so that we can subscribe after hydration when needed.
147 */
148 let unsubscribe: (() => void) | null = null
149β
150 const [queryResource, { refetch, mutate }] = createResource<
151 QueryObserverResult<TData, TError> | undefined
152 >(
153 () => {
154 return new Promise((resolve, reject) => {
155 if (isServer) {
156 unsubscribe = createServerSubscriber(resolve, reject)
157 } else {
158 if (!unsubscribe) {
159 unsubscribe = createClientSubscriber()
160 }
161 }
162 if (!state.isLoading) {
163 resolve(state)
164 }
165 })
166 },
167 {
168 initialValue: state,
169β
170 // If initialData is provided, we resolve the resource immediately
171 ssrLoadFrom: options().initialData ? 'initial' : 'server',
172β
173 get deferStream() {
174 return options().deferStream
175 },
176β
177 /**
178 * If this resource was populated on the server (either sync render, or streamed in over time), onHydrated
179 * will be called. This is the point at which we can hydrate the query cache state, and setup the query subscriber.
180 *
181 * Leveraging onHydrated allows us to plug into the async and streaming support that solidjs resources already support.
182 *
183 * Note that this is only invoked on the client, for queries that were originally run on the server.
184 */
185 onHydrated(_k, info) {
186 if (info.value) {
187 hydrate(client(), {
188 queries: [
189 {
190 queryKey: defaultedOptions.queryKey,
191 queryHash: defaultedOptions.queryHash,
192 state: info.value,
193 },
194 ],
195 })
196 }
197β
198 if (!unsubscribe) {
199 /**
200 * Do not refetch query on mount if query was fetched on server,
201 * even if `staleTime` is not set.
202 */
203 const newOptions = { ...defaultedOptions }
204 if (defaultedOptions.staleTime || !defaultedOptions.initialData) {
205 newOptions.refetchOnMount = false
206 }
207 // Setting the options as an immutable object to prevent
208 // wonky behavior with observer subscriptions
209 observer.setOptions(newOptions)
210 setState(observer.getOptimisticResult(newOptions))
211 unsubscribe = createClientSubscriber()
212 }
213 },
214 },
215 )
216β
217 onCleanup(() => {
218 if (unsubscribe) {
219 unsubscribe()
220 unsubscribe = null
221 }
222 })
223β
224 createComputed(
225 on(
226 () => client().defaultQueryOptions(options()),
227 () => observer.setOptions(client().defaultQueryOptions(options())),
228 {
229 // Defer because we don't need to trigger on first render
230 // This only cares about changes to options after the observer is created
231 defer: true,
232 },
233 ),
234 )
235β
236 createComputed(
237 on(
238 () => state.status,
239 () => {
240 if (
241 state.isError &&
242 !state.isFetching &&
243 shouldThrowError(observer.options.throwOnError, [
244 state.error,
245 observer.getCurrentQuery(),
246 ])
247 ) {
248 throw state.error
249 }
250 },
251 ),
252 )
253β
254 const handler = {
255 get(
256 target: QueryObserverResult<TData, TError>,
257 prop: keyof QueryObserverResult<TData, TError>,
258 ): any {
259 const val = queryResource()?.[prop]
260 return val !== undefined ? val : Reflect.get(target, prop)
261 },
262 }
263β
264 return new Proxy(state, handler)
265}