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

hydration.ts

240 lines6.7 KB

1import type {
2 DefaultError,
3 MutationKey,
4 MutationMeta,
5 MutationOptions,
6 MutationScope,
7 QueryKey,
8 QueryMeta,
9 QueryOptions,
10} from './types'
11import type { QueryClient } from './queryClient'
12import type { Query, QueryState } from './query'
13import type { Mutation, MutationState } from './mutation'
14​
15// TYPES
16type TransformerFn = (data: any) => any
17function defaultTransformerFn(data: any): any {
18 return data
20​
21export interface DehydrateOptions {
22 serializeData?: TransformerFn
23 shouldDehydrateMutation?: (mutation: Mutation) => boolean
24 shouldDehydrateQuery?: (query: Query) => boolean
25 shouldRedactErrors?: (error: unknown) => boolean
27​
28export interface HydrateOptions {
29 defaultOptions?: {
30 deserializeData?: TransformerFn
31 queries?: QueryOptions
32 mutations?: MutationOptions<unknown, DefaultError, unknown, unknown>
33 }
35​
36interface DehydratedMutation {
37 mutationKey?: MutationKey
38 state: MutationState
39 meta?: MutationMeta
40 scope?: MutationScope
42​
43interface DehydratedQuery {
44 queryHash: string
45 queryKey: QueryKey
46 state: QueryState
47 promise?: Promise<unknown>
48 meta?: QueryMeta
50​
51export interface DehydratedState {
52 mutations: Array<DehydratedMutation>
53 queries: Array<DehydratedQuery>
55​
56// FUNCTIONS
57​
58function dehydrateMutation(mutation: Mutation): DehydratedMutation {
59 return {
60 mutationKey: mutation.options.mutationKey,
61 state: mutation.state,
62 ...(mutation.options.scope && { scope: mutation.options.scope }),
63 ...(mutation.meta && { meta: mutation.meta }),
64 }
66​
67// Most config is not dehydrated but instead meant to configure again when
68// consuming the de/rehydrated data, typically with useQuery on the client.
69// Sometimes it might make sense to prefetch data on the server and include
70// in the html-payload, but not consume it on the initial render.
71function dehydrateQuery(
72 query: Query,
73 serializeData: TransformerFn,
74 shouldRedactErrors: (error: unknown) => boolean,
75): DehydratedQuery {
76 return {
77 state: {
78 ...query.state,
79 ...(query.state.data !== undefined && {
80 data: serializeData(query.state.data),
81 }),
82 },
83 queryKey: query.queryKey,
84 queryHash: query.queryHash,
85 ...(query.state.status === 'pending' && {
86 promise: query.promise?.then(serializeData).catch((error) => {
87 if (!shouldRedactErrors(error)) {
88 // Reject original error if it should not be redacted
89 return Promise.reject(error)
90 }
91 // If not in production, log original error before rejecting redacted error
92 if (process.env.NODE_ENV !== 'production') {
93 console.error(
94 `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,
95 )
96 }
97 return Promise.reject(new Error('redacted'))
98 }),
99 }),
100 ...(query.meta && { meta: query.meta }),
101 }
103​
104export function defaultShouldDehydrateMutation(mutation: Mutation) {
105 return mutation.state.isPaused
107​
108export function defaultShouldDehydrateQuery(query: Query) {
109 return query.state.status === 'success'
111​
112export function defaultshouldRedactErrors(_: unknown) {
113 return true
115​
116export function dehydrate(
117 client: QueryClient,
118 options: DehydrateOptions = {},
119): DehydratedState {
120 const filterMutation =
121 options.shouldDehydrateMutation ??
122 client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ??
123 defaultShouldDehydrateMutation
124​
125 const mutations = client
126 .getMutationCache()
127 .getAll()
128 .flatMap((mutation) =>
129 filterMutation(mutation) ? [dehydrateMutation(mutation)] : [],
130 )
131​
132 const filterQuery =
133 options.shouldDehydrateQuery ??
134 client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ??
135 defaultShouldDehydrateQuery
136​
137 const shouldRedactErrors =
138 options.shouldRedactErrors ??
139 client.getDefaultOptions().dehydrate?.shouldRedactErrors ??
140 defaultshouldRedactErrors
141​
142 const serializeData =
143 options.serializeData ??
144 client.getDefaultOptions().dehydrate?.serializeData ??
145 defaultTransformerFn
146​
147 const queries = client
148 .getQueryCache()
149 .getAll()
150 .flatMap((query) =>
151 filterQuery(query)
152 ? [dehydrateQuery(query, serializeData, shouldRedactErrors)]
153 : [],
154 )
155​
156 return { mutations, queries }
158​
159export function hydrate(
160 client: QueryClient,
161 dehydratedState: unknown,
162 options?: HydrateOptions,
163): void {
164 if (typeof dehydratedState !== 'object' || dehydratedState === null) {
165 return
166 }
167​
168 const mutationCache = client.getMutationCache()
169 const queryCache = client.getQueryCache()
170 const deserializeData =
171 options?.defaultOptions?.deserializeData ??
172 client.getDefaultOptions().hydrate?.deserializeData ??
173 defaultTransformerFn
174​
175 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
176 const mutations = (dehydratedState as DehydratedState).mutations || []
177 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
178 const queries = (dehydratedState as DehydratedState).queries || []
179​
180 mutations.forEach(({ state, ...mutationOptions }) => {
181 mutationCache.build(
182 client,
183 {
184 ...client.getDefaultOptions().hydrate?.mutations,
185 ...options?.defaultOptions?.mutations,
186 ...mutationOptions,
187 },
188 state,
189 )
190 })
191​
192 queries.forEach(({ queryKey, state, queryHash, meta, promise }) => {
193 let query = queryCache.get(queryHash)
194​
195 const data =
196 state.data === undefined ? state.data : deserializeData(state.data)
197​
198 // Do not hydrate if an existing query exists with newer data
199 if (query) {
200 if (query.state.dataUpdatedAt < state.dataUpdatedAt) {
201 // omit fetchStatus from dehydrated state
202 // so that query stays in its current fetchStatus
203 const { fetchStatus: _ignored, ...serializedState } = state
204 query.setState({
205 ...serializedState,
206 data,
207 })
208 }
209 } else {
210 // Restore query
211 query = queryCache.build(
212 client,
213 {
214 ...client.getDefaultOptions().hydrate?.queries,
215 ...options?.defaultOptions?.queries,
216 queryKey,
217 queryHash,
218 meta,
219 },
220 // Reset fetch status to idle to avoid
221 // query being stuck in fetching state upon hydration
222 {
223 ...state,
224 data,
225 fetchStatus: 'idle',
226 },
227 )
228 }
229​
230 if (promise) {
231 // Note: `Promise.resolve` required cause
232 // RSC transformed promises are not thenable
233 const initialPromise = Promise.resolve(promise).then(deserializeData)
234​
235 // this doesn't actually fetch - it just creates a retryer
236 // which will re-use the passed `initialPromise`
237 void query.fetch(undefined, { initialPromise })
238 }
239 })