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

hydration.ts

337 lines10.3 KB

1import { noop } from './utils'
2import type {
3 DefaultError,
4 MutationKey,
5 MutationMeta,
6 MutationOptions,
7 MutationScope,
8 QueryKey,
9 QueryMeta,
10 QueryOptions,
11} from './types'
12import type { QueryClient } from './queryClient'
13import type { Query, QueryState } from './query'
14import type { Mutation, MutationState } from './mutation'
15​
16// TYPES
17type TransformerFn = (data: any) => any
18function defaultTransformerFn(data: any): any {
19 return data
21​
22function tryResolveSync(promise: PromiseLike<unknown>) {
23 let data: unknown
24​
25 const thenResult = promise.then((result) => {
26 data = result
27 return result
28 }, noop) as Promise<unknown> | undefined
29​
30 // .catch can be unavailable on certain kinds of thenable's
31 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
32 thenResult?.catch?.(noop)
33​
34 if (data !== undefined) {
35 return { data }
36 }
37​
38 return undefined
40​
41export interface DehydrateOptions {
42 serializeData?: TransformerFn
43 shouldDehydrateMutation?: (mutation: Mutation) => boolean
44 shouldDehydrateQuery?: (query: Query) => boolean
45 shouldRedactErrors?: (error: unknown) => boolean
47​
48export interface HydrateOptions {
49 defaultOptions?: {
50 deserializeData?: TransformerFn
51 queries?: QueryOptions
52 mutations?: MutationOptions<unknown, DefaultError, unknown, unknown>
53 }
55​
56interface DehydratedMutation {
57 mutationKey?: MutationKey
58 state: MutationState
59 meta?: MutationMeta
60 scope?: MutationScope
62​
63interface DehydratedQuery {
64 queryHash: string
65 queryKey: QueryKey
66 state: QueryState
67 promise?: Promise<unknown>
68 meta?: QueryMeta
69 queryType?: 'infinite'
70 // This is only optional because older versions of Query might have dehydrated
71 // without it which we need to handle for backwards compatibility.
72 // This should be changed to required in the future.
73 dehydratedAt?: number
75​
76export interface DehydratedState {
77 mutations: Array<DehydratedMutation>
78 queries: Array<DehydratedQuery>
80​
81// FUNCTIONS
82​
83function dehydrateMutation(mutation: Mutation): DehydratedMutation {
84 return {
85 mutationKey: mutation.options.mutationKey,
86 state: mutation.state,
87 ...(mutation.options.scope && { scope: mutation.options.scope }),
88 ...(mutation.meta && { meta: mutation.meta }),
89 }
91​
92// Most config is not dehydrated but instead meant to configure again when
93// consuming the de/rehydrated data, typically with useQuery on the client.
94// Sometimes it might make sense to prefetch data on the server and include
95// in the html-payload, but not consume it on the initial render.
96function dehydrateQuery(
97 query: Query,
98 serializeData: TransformerFn,
99 shouldRedactErrors: (error: unknown) => boolean,
100): DehydratedQuery {
101 const dehydratePromise = () => {
102 const promise = query.promise?.then(serializeData).catch((error) => {
103 if (!shouldRedactErrors(error)) {
104 // Reject original error if it should not be redacted
105 return Promise.reject(error)
106 }
107 // If not in production, log original error before rejecting redacted error
108 if (process.env.NODE_ENV !== 'production') {
109 console.error(
110 `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,
111 )
112 }
113 return Promise.reject(new Error('redacted'))
114 })
115​
116 // Avoid unhandled promise rejections
117 // We need the promise we dehydrate to reject to get the correct result into
118 // the query cache, but we also want to avoid unhandled promise rejections
119 // in whatever environment the prefetches are happening in.
120 promise?.catch(noop)
121​
122 return promise
123 }
124​
125 return {
126 dehydratedAt: Date.now(),
127 state: {
128 ...query.state,
129 ...(query.state.data !== undefined && {
130 data: serializeData(query.state.data),
131 }),
132 },
133 queryKey: query.queryKey,
134 queryHash: query.queryHash,
135 ...(query.state.status === 'pending' && {
136 promise: dehydratePromise(),
137 }),
138 ...(query.meta && { meta: query.meta }),
139 ...(query.queryType && { queryType: query.queryType }),
140 }
142​
143export function defaultShouldDehydrateMutation(mutation: Mutation) {
144 return mutation.state.isPaused
146​
147export function defaultShouldDehydrateQuery(query: Query) {
148 return query.state.status === 'success'
150​
151function defaultShouldRedactErrors(_: unknown) {
152 return true
154​
155export function dehydrate(
156 client: QueryClient,
157 options: DehydrateOptions = {},
158): DehydratedState {
159 const filterMutation =
160 options.shouldDehydrateMutation ??
161 client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ??
162 defaultShouldDehydrateMutation
163​
164 const mutations = client
165 .getMutationCache()
166 .getAll()
167 .flatMap((mutation) =>
168 filterMutation(mutation) ? [dehydrateMutation(mutation)] : [],
169 )
170​
171 const filterQuery =
172 options.shouldDehydrateQuery ??
173 client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ??
174 defaultShouldDehydrateQuery
175​
176 const shouldRedactErrors =
177 options.shouldRedactErrors ??
178 client.getDefaultOptions().dehydrate?.shouldRedactErrors ??
179 defaultShouldRedactErrors
180​
181 const serializeData =
182 options.serializeData ??
183 client.getDefaultOptions().dehydrate?.serializeData ??
184 defaultTransformerFn
185​
186 const queries = client
187 .getQueryCache()
188 .getAll()
189 .flatMap((query) =>
190 filterQuery(query)
191 ? [dehydrateQuery(query, serializeData, shouldRedactErrors)]
192 : [],
193 )
194​
195 return { mutations, queries }
197​
198export function hydrate(
199 client: QueryClient,
200 dehydratedState: unknown,
201 options?: HydrateOptions,
202): void {
203 if (typeof dehydratedState !== 'object' || dehydratedState === null) {
204 return
205 }
206​
207 const mutationCache = client.getMutationCache()
208 const queryCache = client.getQueryCache()
209 const deserializeData =
210 options?.defaultOptions?.deserializeData ??
211 client.getDefaultOptions().hydrate?.deserializeData ??
212 defaultTransformerFn
213​
214 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
215 const mutations = (dehydratedState as DehydratedState).mutations || []
216 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
217 const queries = (dehydratedState as DehydratedState).queries || []
218​
219 mutations.forEach(({ state, ...mutationOptions }) => {
220 mutationCache.build(
221 client,
222 {
223 ...client.getDefaultOptions().hydrate?.mutations,
224 ...options?.defaultOptions?.mutations,
225 ...mutationOptions,
226 },
227 state,
228 )
229 })
230​
231 queries.forEach(
232 ({
233 queryKey,
234 state,
235 queryHash,
236 meta,
237 promise,
238 dehydratedAt,
239 queryType,
240 }) => {
241 const syncData = promise ? tryResolveSync(promise) : undefined
242 const rawData = state.data === undefined ? syncData?.data : state.data
243 const data = rawData === undefined ? rawData : deserializeData(rawData)
244​
245 let query = queryCache.get(queryHash)
246 const existingQueryIsPending = query?.state.status === 'pending'
247 const existingQueryIsFetching = query?.state.fetchStatus === 'fetching'
248​
249 // Do not hydrate if an existing query exists with newer data
250 if (query) {
251 const hasNewerSyncData =
252 syncData &&
253 // We only need this undefined check to handle older dehydration
254 // payloads that might not have dehydratedAt
255 dehydratedAt !== undefined &&
256 dehydratedAt > query.state.dataUpdatedAt
257 if (
258 state.dataUpdatedAt > query.state.dataUpdatedAt ||
259 hasNewerSyncData
260 ) {
261 // Omit fetchStatus from dehydrated state so that query stays in its current fetchStatus
262 const { fetchStatus: _ignored, ...serializedState } = state
263 query.setState({
264 ...serializedState,
265 data,
266 // If the query was pending at the moment of dehydration, but resolved to have data
267 // before hydration, we can assume the query should be hydrated as successful.
268 //
269 // Since you can opt into dehydrating failed queries, and those can have data from
270 // previous successful fetches, we make sure we only do this for pending queries.
271 ...(state.status === 'pending' &&
272 data !== undefined && {
273 status: 'success' as const,
274 dataUpdatedAt: dehydratedAt ?? Date.now(),
275 // Preserve existing fetchStatus if the existing query is actively fetching.
276 ...(!existingQueryIsFetching && {
277 fetchStatus: 'idle' as const,
278 }),
279 }),
280 })
281 }
282 } else {
283 // Restore query
284 query = queryCache.build(
285 client,
286 {
287 ...client.getDefaultOptions().hydrate?.queries,
288 ...options?.defaultOptions?.queries,
289 queryKey,
290 queryHash,
291 meta,
292 _type: queryType,
293 },
294 // Reset fetch status to idle to avoid
295 // query being stuck in fetching state upon hydration
296 {
297 ...state,
298 data,
299 fetchStatus: 'idle',
300 // Like above, if the query was pending at the moment of dehydration but has data,
301 // we can assume it should be hydrated as successful.
302 status:
303 state.status === 'pending' && data !== undefined
304 ? 'success'
305 : state.status,
306 ...(state.status === 'pending' &&
307 data !== undefined && {
308 dataUpdatedAt: dehydratedAt ?? Date.now(),
309 }),
310 },
311 )
312 }
313​
314 if (
315 promise &&
316 // If the data was synchronously available, there is no need to set up
317 // a retryer and thus no reason to call fetch
318 !syncData &&
319 !existingQueryIsPending &&
320 !existingQueryIsFetching &&
321 // Only hydrate if dehydration is newer than any existing data,
322 // this is always true for new queries
323 (dehydratedAt === undefined || dehydratedAt > query.state.dataUpdatedAt)
324 ) {
325 // This doesn't actually fetch - it just creates a retryer
326 // which will re-use the passed `initialPromise`
327 query
328 .fetch(undefined, {
329 // RSC transformed promises are not thenable
330 initialPromise: Promise.resolve(promise).then(deserializeData),
331 })
332 // Avoid unhandled promise rejections
333 .catch(noop)
334 }
335 },
336 )