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

hydration.ts

483 lines16.0 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
18​
19/**
20 * Reads the value of a promise synchronously if it has already resolved, e.g. a
21 * thenable that resolves within its `then` call.
22 *
23 * @param promise - The promise to read.
24 * @returns An object with the resolved `data`, or `undefined` if the promise
25 * hasn't resolved synchronously (or resolved with `undefined`).
26 */
27function tryResolveSync(promise: PromiseLike<unknown>) {
28 let data: unknown
29​
30 const thenResult = promise.then((result) => {
31 data = result
32 return result
33 }, noop) as Promise<unknown> | undefined
34​
35 // .catch can be unavailable on certain kinds of thenable's
36 // oxlint-disable-next-line typescript/no-unnecessary-condition
37 thenResult?.catch?.(noop)
38​
39 if (data !== undefined) {
40 return { data }
41 }
42​
43 return undefined
45​
46/**
47 * Options for `dehydrate`, controlling which queries/mutations are included in
48 * the resulting `DehydratedState` and how their data/errors are transformed
49 * before being serialized (e.g. for embedding in server-rendered markup).
50 */
51export interface DehydrateOptions {
52 /**
53 * Transforms a query's `data` before it is dehydrated. Useful for
54 * non-JSON-serializable data.
55 */
56 serializeData?: TransformerFn
57 /**
58 * Predicate to decide whether a given `Mutation` should be dehydrated.
59 * Defaults to `defaultShouldDehydrateMutation`.
60 */
61 shouldDehydrateMutation?: (mutation: Mutation) => boolean
62 /**
63 * Predicate to decide whether a given `Query` should be dehydrated. Defaults
64 * to `defaultShouldDehydrateQuery`.
65 */
66 shouldDehydrateQuery?: (query: Query) => boolean
67 /**
68 * Predicate to decide whether a query's error should be redacted before
69 * dehydration. Errors are redacted (replaced with a generic
70 * `Error('redacted')`) unless this function is provided and returns `false`
71 * for the given error, in which case the original error is kept.
72 */
73 shouldRedactErrors?: (error: unknown) => boolean
75​
76/**
77 * Options for `hydrate`, controlling the default options applied to
78 * queries/mutations restored from a `DehydratedState`, and how to reverse any
79 * transformation applied by `DehydrateOptions.serializeData`.
80 */
81export interface HydrateOptions {
82 /**
83 * Options applied to the queries and mutations restored from the dehydrated
84 * state.
85 */
86 defaultOptions?: {
87 /**
88 * Transforms a query's `data` after it is read from the dehydrated state,
89 * reversing `serializeData`.
90 */
91 deserializeData?: TransformerFn
92 /**
93 * Default options merged into every query restored from the dehydrated
94 * state.
95 */
96 queries?: QueryOptions
97 /**
98 * Default options merged into every mutation restored from the dehydrated
99 * state.
100 */
101 mutations?: MutationOptions<unknown, DefaultError, unknown, unknown>
102 }
104​
105interface DehydratedMutation {
106 mutationKey?: MutationKey
107 state: MutationState
108 meta?: MutationMeta
109 scope?: MutationScope
111​
112interface DehydratedQuery {
113 queryHash: string
114 queryKey: QueryKey
115 state: QueryState
116 dehydratedAt: number
117 promise?: Promise<unknown>
118 meta?: QueryMeta
119 queryType?: 'infinite'
121​
122/**
123 * A serializable snapshot of a `QueryClient`'s cache, as produced by
124 * `dehydrate` and consumed by `hydrate`. Typically transported from server to
125 * client (e.g. embedded in server-rendered markup) to seed the client's cache
126 * with data that has already been fetched, avoiding a redundant fetch on the
127 * client.
128 */
129export interface DehydratedState {
130 /** The dehydrated mutations, by default only the paused ones. */
131 mutations: Array<DehydratedMutation>
132 /** The dehydrated queries, by default only the successful ones. */
133 queries: Array<DehydratedQuery>
135​
136// FUNCTIONS
137​
138/**
139 * Dehydrates a single `Mutation` into a serializable snapshot of its key,
140 * state, scope, and meta.
141 *
142 * @param mutation - The mutation to dehydrate.
143 * @returns The dehydrated mutation.
144 */
145function dehydrateMutation(mutation: Mutation): DehydratedMutation {
146 return {
147 mutationKey: mutation.options.mutationKey,
148 state: mutation.state,
149 ...(mutation.options.scope && { scope: mutation.options.scope }),
150 ...(mutation.meta && { meta: mutation.meta }),
151 }
153​
154/**
155 * Prepares the in-flight promise of a pending query for dehydration: applies
156 * `serializeData` to its result, and redacts its rejection error unless
157 * `shouldRedactErrors` returns `false` for it.
158 *
159 * @param query - The pending query whose promise is dehydrated.
160 * @param serializeData - Optional transform applied to the resolved data.
161 * @param shouldRedactErrors - Optional predicate; if it returns `false` for the
162 * rejection error, that error is kept as-is instead of being redacted.
163 * @returns The transformed promise, or `undefined` if the query has no
164 * in-flight promise.
165 */
166function dehydratePromise(
167 query: Query,
168 serializeData?: TransformerFn,
169 shouldRedactErrors?: (error: unknown) => boolean,
170): Promise<unknown> | undefined {
171 const promise = query.promise?.then(serializeData).catch((error) => {
172 if (shouldRedactErrors?.(error) === false) {
173 // Reject original error if it should not be redacted
174 return Promise.reject(error)
175 }
176 // If not in production, log original error before rejecting redacted error
177 if (process.env.NODE_ENV !== 'production') {
178 console.error(
179 `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,
180 )
181 }
182 return Promise.reject(new Error('redacted'))
183 })
184​
185 // Avoid unhandled promise rejections
186 // We need the promise we dehydrate to reject to get the correct result into
187 // the query cache, but we also want to avoid unhandled promise rejections
188 // in whatever environment the prefetches are happening in.
189 promise?.catch(noop)
190​
191 return promise
193​
194/**
195 * Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot.
196 * Note that most query config (e.g. `queryFn`, `staleTime`) is not dehydrated
197 * but instead meant to be configured again when consuming the de/rehydrated
198 * data, typically with `useQuery` on the client. If the query is still
199 * `pending`, its in-flight promise is dehydrated too so it can be resumed on
200 * the other side instead of re-fetched.
201 *
202 * @param query - The query to dehydrate.
203 * @param serializeData - Optional transform applied to `query.state.data`
204 * before it is included in the snapshot.
205 * @param shouldRedactErrors - Optional predicate; if it returns `false` for the
206 * promise's rejection error, that error is kept as-is instead of being
207 * redacted.
208 * @returns The dehydrated query.
209 */
210export function dehydrateQuery(
211 query: Query,
212 serializeData?: TransformerFn,
213 shouldRedactErrors?: (error: unknown) => boolean,
214): DehydratedQuery {
215 return {
216 dehydratedAt: Date.now(),
217 state: {
218 ...query.state,
219 ...(query.state.data !== undefined && {
220 data: serializeData
221 ? serializeData(query.state.data)
222 : query.state.data,
223 }),
224 },
225 queryKey: query.queryKey,
226 queryHash: query.queryHash,
227 ...(query.state.status === 'pending' && {
228 promise: dehydratePromise(query, serializeData, shouldRedactErrors),
229 }),
230 ...(query.meta && { meta: query.meta }),
231 ...(query.queryType && { queryType: query.queryType }),
232 }
234​
235/**
236 * The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only
237 * dehydrates mutations that are currently paused (e.g. paused by `networkMode`
238 * while offline).
239 *
240 * @param mutation - The mutation to check.
241 * @returns `true` if the mutation is paused.
242 */
243export function defaultShouldDehydrateMutation(mutation: Mutation) {
244 return mutation.state.isPaused
246​
247/**
248 * The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only
249 * dehydrates queries whose status is `'success'`.
250 *
251 * @param query - The query to check.
252 * @returns `true` if the query's status is `'success'`.
253 */
254export function defaultShouldDehydrateQuery(query: Query) {
255 return query.state.status === 'success'
257​
258/**
259 * Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain,
260 * serializable `DehydratedState`, typically to embed in server-rendered markup
261 * and later restore into a client-side `QueryClient` via `hydrate`. Which
262 * queries/mutations are included, and how their data/errors are transformed, is
263 * controlled by `options`, falling back to the client's `dehydrate` default
264 * options, and finally to `defaultShouldDehydrateQuery` /
265 * `defaultShouldDehydrateMutation`.
266 *
267 * @example
268 * ;```ts
269 * const queryClient = new QueryClient()
270 *
271 * await queryClient.prefetchQuery({
272 * queryKey: ['posts'],
273 * queryFn: getPosts,
274 * })
275 *
276 * const dehydratedState = dehydrate(queryClient)
277 * ```
278 *
279 * @param client - The client whose cache is dehydrated.
280 * @param options - Controls which queries and mutations are included and how
281 * their data and errors are transformed. Each option falls back to the
282 * client's `defaultOptions.dehydrate`.
283 * @returns The dehydrated state, with the included `queries` and `mutations`.
284 */
285export function dehydrate(
286 client: QueryClient,
287 options: DehydrateOptions = {},
288): DehydratedState {
289 const filterMutation =
290 options.shouldDehydrateMutation ??
291 client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ??
292 defaultShouldDehydrateMutation
293​
294 const mutations = client
295 .getMutationCache()
296 .getAll()
297 .flatMap((mutation) =>
298 filterMutation(mutation) ? [dehydrateMutation(mutation)] : [],
299 )
300​
301 const filterQuery =
302 options.shouldDehydrateQuery ??
303 client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ??
304 defaultShouldDehydrateQuery
305​
306 const shouldRedactErrors =
307 options.shouldRedactErrors ??
308 client.getDefaultOptions().dehydrate?.shouldRedactErrors
309​
310 const serializeData =
311 options.serializeData ?? client.getDefaultOptions().dehydrate?.serializeData
312​
313 const queries = client
314 .getQueryCache()
315 .getAll()
316 .flatMap((query) =>
317 filterQuery(query)
318 ? [dehydrateQuery(query, serializeData, shouldRedactErrors)]
319 : [],
320 )
321​
322 return { mutations, queries }
324​
325/**
326 * Restores a `DehydratedState` (as produced by `dehydrate`) into a
327 * `QueryClient`'s cache, typically to seed the client with data already fetched
328 * on the server. `mutations` and `queries` are each optional on
329 * `dehydratedState`. Queries not yet in the cache are built from the dehydrated
330 * snapshot; queries that already exist are only updated when the dehydrated
331 * data is newer than what's already cached. Newly built queries have their
332 * `fetchStatus` reset to `'idle'` so they don't hydrate stuck in a fetching
333 * state. If a dehydrated query still had an in-flight promise, it is resumed
334 * via `query.fetch()` (reusing that promise as `initialPromise`) rather than
335 * re-invoking `queryFn`.
336 *
337 * @example
338 * ```ts
339 * // dehydratedState was produced by `dehydrate` on the server
340 * // and sent to the client, e.g. embedded in server-rendered markup.
341 * const queryClient = new QueryClient()
342 *
343 * hydrate(queryClient, dehydratedState)
344 * ```
345 *
346 * @param client - The client whose cache is restored into.
347 * @param dehydratedState - The dehydrated state, e.g. produced by `dehydrate`
348 * on the server.
349 * @param options - `defaultOptions` merged into every restored query and
350 * mutation (on top of the client's `defaultOptions.hydrate`), and
351 * `deserializeData` to reverse `serializeData`.
352 */
353export function hydrate(
354 client: QueryClient,
355 dehydratedState: Partial<DehydratedState>,
356 options?: HydrateOptions,
357): void {
358 const mutationCache = client.getMutationCache()
359 const queryCache = client.getQueryCache()
360 const deserializeData =
361 options?.defaultOptions?.deserializeData ??
362 client.getDefaultOptions().hydrate?.deserializeData
363​
364 dehydratedState.mutations?.forEach(({ state, ...mutationOptions }) => {
365 mutationCache.build(
366 client,
367 {
368 ...client.getDefaultOptions().hydrate?.mutations,
369 ...options?.defaultOptions?.mutations,
370 ...mutationOptions,
371 },
372 state,
373 )
374 })
375​
376 dehydratedState.queries?.forEach(
377 ({
378 queryKey,
379 state,
380 queryHash,
381 meta,
382 promise,
383 dehydratedAt,
384 queryType,
385 }) => {
386 const syncData = promise ? tryResolveSync(promise) : undefined
387 const rawData = state.data === undefined ? syncData?.data : state.data
388 const data =
389 rawData === undefined
390 ? rawData
391 : deserializeData
392 ? deserializeData(rawData)
393 : rawData
394​
395 let query = queryCache.get(queryHash)
396 const existingQueryIsPending = query?.state.status === 'pending'
397 const existingQueryIsFetching = query?.state.fetchStatus === 'fetching'
398​
399 // Do not hydrate if an existing query exists with newer data
400 if (query) {
401 const hasNewerSyncData =
402 syncData && dehydratedAt > query.state.dataUpdatedAt
403 if (
404 state.dataUpdatedAt > query.state.dataUpdatedAt ||
405 hasNewerSyncData
406 ) {
407 // Omit fetchStatus from dehydrated state so that query stays in its current fetchStatus
408 const { fetchStatus: _ignored, ...serializedState } = state
409 query.setState({
410 ...serializedState,
411 data,
412 // If the query was pending at the moment of dehydration, but resolved to have data
413 // before hydration, we can assume the query should be hydrated as successful.
414 //
415 // Since you can opt into dehydrating failed queries, and those can have data from
416 // previous successful fetches, we make sure we only do this for pending queries.
417 ...(state.status === 'pending' &&
418 data !== undefined && {
419 status: 'success' as const,
420 dataUpdatedAt: dehydratedAt,
421 // Preserve existing fetchStatus if the existing query is actively fetching.
422 ...(!existingQueryIsFetching && {
423 fetchStatus: 'idle' as const,
424 }),
425 }),
426 })
427 }
428 } else {
429 // Restore query
430 query = queryCache.build(
431 client,
432 {
433 ...client.getDefaultOptions().hydrate?.queries,
434 ...options?.defaultOptions?.queries,
435 queryKey,
436 queryHash,
437 meta,
438 _type: queryType,
439 },
440 // Reset fetch status to idle to avoid
441 // query being stuck in fetching state upon hydration
442 {
443 ...state,
444 data,
445 fetchStatus: 'idle',
446 // Like above, if the query was pending at the moment of dehydration but has data,
447 // we can assume it should be hydrated as successful.
448 status:
449 state.status === 'pending' && data !== undefined
450 ? 'success'
451 : state.status,
452 ...(state.status === 'pending' &&
453 data !== undefined && {
454 dataUpdatedAt: dehydratedAt,
455 }),
456 },
457 )
458 }
459​
460 if (
461 promise &&
462 // If the data was synchronously available, there is no need to set up
463 // a retryer and thus no reason to call fetch
464 !syncData &&
465 !existingQueryIsPending &&
466 !existingQueryIsFetching &&
467 // Only hydrate if dehydration is newer than any existing data,
468 // this is always true for new queries
469 dehydratedAt > query.state.dataUpdatedAt
470 ) {
471 // This doesn't actually fetch - it just creates a retryer
472 // which will re-use the passed `initialPromise`
473 query
474 .fetch(undefined, {
475 // RSC transformed promises are not thenable
476 initialPromise: Promise.resolve(promise).then(deserializeData),
477 })
478 // Avoid unhandled promise rejections
479 .catch(noop)
480 }
481 },
482 )