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