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

createBaseQuery.ts

220 lines6.2 KB

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