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

hydration.ts

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