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