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

hydration.ts

319 lines9.9 KB

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