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