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