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 promise = query.promise?.then(serializeData).catch((error) => {
83 if (!shouldRedactErrors(error)) {
84 // Reject original error if it should not be redacted
85 return Promise.reject(error)
86 }
87 // If not in production, log original error before rejecting redacted error
88 if (process.env.NODE_ENV !== 'production') {
89 console.error(
90 `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,
91 )
92 }
93 return Promise.reject(new Error('redacted'))
94 })
95β
96 // Avoid unhandled promise rejections
97 // We need the promise we dehydrate to reject to get the correct result into
98 // the query cache, but we also want to avoid unhandled promise rejections
99 // in whatever environment the prefetches are happening in.
100 promise?.catch(noop)
101β
102 return {
103 dehydratedAt: Date.now(),
104 state: {
105 ...query.state,
106 ...(query.state.data !== undefined && {
107 data: serializeData(query.state.data),
108 }),
109 },
110 queryKey: query.queryKey,
111 queryHash: query.queryHash,
112 ...(query.state.status === 'pending' && {
113 promise,
114 }),
115 ...(query.meta && { meta: query.meta }),
116 }
117}
118β
119export function defaultShouldDehydrateMutation(mutation: Mutation) {
120 return mutation.state.isPaused
121}
122β
123export function defaultShouldDehydrateQuery(query: Query) {
124 return query.state.status === 'success'
125}
126β
127function defaultShouldRedactErrors(_: unknown) {
128 return true
129}
130β
131export function dehydrate(
132 client: QueryClient,
133 options: DehydrateOptions = {},
134): DehydratedState {
135 const filterMutation =
136 options.shouldDehydrateMutation ??
137 client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ??
138 defaultShouldDehydrateMutation
139β
140 const mutations = client
141 .getMutationCache()
142 .getAll()
143 .flatMap((mutation) =>
144 filterMutation(mutation) ? [dehydrateMutation(mutation)] : [],
145 )
146β
147 const filterQuery =
148 options.shouldDehydrateQuery ??
149 client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ??
150 defaultShouldDehydrateQuery
151β
152 const shouldRedactErrors =
153 options.shouldRedactErrors ??
154 client.getDefaultOptions().dehydrate?.shouldRedactErrors ??
155 defaultShouldRedactErrors
156β
157 const serializeData =
158 options.serializeData ??
159 client.getDefaultOptions().dehydrate?.serializeData ??
160 defaultTransformerFn
161β
162 const queries = client
163 .getQueryCache()
164 .getAll()
165 .flatMap((query) =>
166 filterQuery(query)
167 ? [dehydrateQuery(query, serializeData, shouldRedactErrors)]
168 : [],
169 )
170β
171 return { mutations, queries }
172}
173β
174export function hydrate(
175 client: QueryClient,
176 dehydratedState: unknown,
177 options?: HydrateOptions,
178): void {
179 if (typeof dehydratedState !== 'object' || dehydratedState === null) {
180 return
181 }
182β
183 const mutationCache = client.getMutationCache()
184 const queryCache = client.getQueryCache()
185 const deserializeData =
186 options?.defaultOptions?.deserializeData ??
187 client.getDefaultOptions().hydrate?.deserializeData ??
188 defaultTransformerFn
189β
190 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
191 const mutations = (dehydratedState as DehydratedState).mutations || []
192 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
193 const queries = (dehydratedState as DehydratedState).queries || []
194β
195 mutations.forEach(({ state, ...mutationOptions }) => {
196 mutationCache.build(
197 client,
198 {
199 ...client.getDefaultOptions().hydrate?.mutations,
200 ...options?.defaultOptions?.mutations,
201 ...mutationOptions,
202 },
203 state,
204 )
205 })
206β
207 queries.forEach(
208 ({ queryKey, state, queryHash, meta, promise, dehydratedAt }) => {
209 const syncData = promise ? tryResolveSync(promise) : undefined
210 const rawData = state.data === undefined ? syncData?.data : state.data
211 const data = rawData === undefined ? rawData : deserializeData(rawData)
212β
213 let query = queryCache.get(queryHash)
214 const existingQueryIsPending = query?.state.status === 'pending'
215 const existingQueryIsFetching = query?.state.fetchStatus === 'fetching'
216β
217 // Do not hydrate if an existing query exists with newer data
218 if (query) {
219 const hasNewerSyncData =
220 syncData &&
221 // We only need this undefined check to handle older dehydration
222 // payloads that might not have dehydratedAt
223 dehydratedAt !== undefined &&
224 dehydratedAt > query.state.dataUpdatedAt
225 if (
226 state.dataUpdatedAt > query.state.dataUpdatedAt ||
227 hasNewerSyncData
228 ) {
229 // omit fetchStatus from dehydrated state
230 // so that query stays in its current fetchStatus
231 const { fetchStatus: _ignored, ...serializedState } = state
232 query.setState({
233 ...serializedState,
234 data,
235 })
236 }
237 } else {
238 // Restore query
239 query = queryCache.build(
240 client,
241 {
242 ...client.getDefaultOptions().hydrate?.queries,
243 ...options?.defaultOptions?.queries,
244 queryKey,
245 queryHash,
246 meta,
247 },
248 // Reset fetch status to idle to avoid
249 // query being stuck in fetching state upon hydration
250 {
251 ...state,
252 data,
253 fetchStatus: 'idle',
254 status: data !== undefined ? 'success' : state.status,
255 },
256 )
257 }
258β
259 if (
260 promise &&
261 !existingQueryIsPending &&
262 !existingQueryIsFetching &&
263 // Only hydrate if dehydration is newer than any existing data,
264 // this is always true for new queries
265 (dehydratedAt === undefined || dehydratedAt > query.state.dataUpdatedAt)
266 ) {
267 // This doesn't actually fetch - it just creates a retryer
268 // which will re-use the passed `initialPromise`
269 // Note that we need to call these even when data was synchronously
270 // available, as we still need to set up the retryer
271 query
272 .fetch(undefined, {
273 // RSC transformed promises are not thenable
274 initialPromise: Promise.resolve(promise).then(deserializeData),
275 })
276 // Avoid unhandled promise rejections
277 .catch(noop)
278 }
279 },
280 )
281}