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