Open History to see the last commit
1import { dehydrate, hydrate } from '@tanstack/query-core'
2import type {
3 DehydrateOptions,
4 DehydratedState,
5 HydrateOptions,
6 NotifyEventType,
7 QueryClient,
8} from '@tanstack/query-core'
9β
10/**
11 * A value, or a promise-like that resolves to it.
12 */
13export type Promisable<T> = T | PromiseLike<T>
14β
15/**
16 * Saves, restores, and removes a {@link PersistedClient} in a storage.
17 */
18export interface Persister {
19 /**
20 * Saves the persisted client to the storage.
21 */
22 persistClient: (persistClient: PersistedClient) => Promisable<void>
23 /**
24 * Reads the persisted client from the storage, or `undefined` if nothing was saved.
25 */
26 restoreClient: () => Promisable<PersistedClient | undefined>
27 /**
28 * Removes the persisted client from the storage.
29 */
30 removeClient: () => Promisable<void>
31}
32β
33/**
34 * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its
35 * `buster`.
36 */
37export interface PersistedClient {
38 /**
39 * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.
40 */
41 timestamp: number
42 /**
43 * The `buster` the client was saved with. A persisted client with a different `buster` is
44 * discarded.
45 */
46 buster: string
47 /**
48 * The dehydrated cache of the `QueryClient`.
49 */
50 clientState: DehydratedState
51}
52β
53/**
54 * The options shared by restoring and saving a persisted `QueryClient`.
55 */
56export interface PersistQueryClientRootOptions {
57 /** The QueryClient to persist */
58 queryClient: QueryClient
59 /**
60 * The Persister interface for storing and restoring the cache
61 * to/from a persisted location
62 */
63 persister: Persister
64 /**
65 * A unique string that can be used to forcefully
66 * invalidate existing caches if they do not share the same buster string
67 */
68 buster?: string
69}
70β
71/**
72 * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.
73 */
74export interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {
75 /**
76 * The max-allowed age of the cache in milliseconds.
77 * If a persisted cache is found that is older than this
78 * time, it will be discarded
79 */
80 maxAge?: number
81 /** The options passed to the hydrate function */
82 hydrateOptions?: HydrateOptions
83}
84β
85/**
86 * Options for saving a `QueryClient` with {@link persistQueryClientSave}.
87 */
88export interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {
89 /** The options passed to the dehydrate function */
90 dehydrateOptions?: DehydrateOptions
91}
92β
93/**
94 * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.
95 */
96export interface PersistQueryClientOptions
97 extends
98 PersistedQueryClientRestoreOptions,
99 PersistedQueryClientSaveOptions,
100 PersistQueryClientRootOptions {}
101β
102const cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']
103β
104/**
105 * Checks if emitted event is about cache change and not about observers.
106 * Useful for persist, where we only want to trigger save when cache is changed.
107 * @param eventType - The type of the emitted event.
108 * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.
109 */
110function isCacheEventType(eventType: NotifyEventType) {
111 return cacheEventTypes.includes(eventType)
112}
113β
114/**
115 * Restores persisted data to the QueryCache.
116 * - data obtained from persister.restoreClient.
117 * - data is hydrated using hydrateOptions.
118 * If data is expired, busted, empty, or throws, it runs persister.removeClient.
119 * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,
120 * and `hydrateOptions` that decide whether and how the persisted data is restored.
121 * @returns A promise that resolves once the data is restored or removed. If restoring throws, it
122 * attempts to remove the persisted data and then rejects with the restore error, or with the removal
123 * error if the removal fails too.
124 */
125export async function persistQueryClientRestore({
126 queryClient,
127 persister,
128 maxAge = 24 * 60 * 60 * 1000,
129 buster = '',
130 hydrateOptions,
131}: PersistedQueryClientRestoreOptions) {
132 try {
133 const persistedClient = await persister.restoreClient()
134β
135 if (persistedClient) {
136 if (persistedClient.timestamp) {
137 const expired = Date.now() - persistedClient.timestamp > maxAge
138 const busted = persistedClient.buster !== buster
139 if (expired || busted) {
140 return persister.removeClient()
141 } else {
142 hydrate(queryClient, persistedClient.clientState, hydrateOptions)
143 }
144 } else {
145 return persister.removeClient()
146 }
147 }
148 } catch (err) {
149 if (process.env.NODE_ENV !== 'production') {
150 console.error(err)
151 console.warn(
152 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',
153 )
154 }
155β
156 await persister.removeClient()
157β
158 throw err
159 }
160}
161β
162/**
163 * Persists data from the QueryCache.
164 * - data dehydrated using dehydrateOptions.
165 * - data is persisted using persister.persistClient.
166 * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the
167 * `dehydrateOptions`.
168 */
169export async function persistQueryClientSave({
170 queryClient,
171 persister,
172 buster = '',
173 dehydrateOptions,
174}: PersistedQueryClientSaveOptions) {
175 const persistClient: PersistedClient = {
176 buster,
177 timestamp: Date.now(),
178 clientState: dehydrate(queryClient, dehydrateOptions),
179 }
180β
181 await persister.persistClient(persistClient)
182}
183β
184/**
185 * Subscribe to QueryCache and MutationCache updates (for persisting).
186 * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the
187 * `dehydrateOptions` used for each save.
188 * @returns an unsubscribe function (to discontinue monitoring)
189 */
190export function persistQueryClientSubscribe(
191 props: PersistedQueryClientSaveOptions,
192) {
193 const save = () => {
194 persistQueryClientSave(props).catch((err) => {
195 if (process.env.NODE_ENV !== 'production') {
196 console.error(err)
197 console.warn(
198 'Encountered an error attempting to persist client cache to persisted location.',
199 )
200 }
201 })
202 }
203β
204 const unsubscribeQueryCache = props.queryClient
205 .getQueryCache()
206 .subscribe((event) => {
207 if (isCacheEventType(event.type)) {
208 save()
209 }
210 })
211β
212 const unsubscribeMutationCache = props.queryClient
213 .getMutationCache()
214 .subscribe((event) => {
215 if (isCacheEventType(event.type)) {
216 save()
217 }
218 })
219β
220 return () => {
221 unsubscribeQueryCache()
222 unsubscribeMutationCache()
223 }
224}
225β
226/**
227 * Restores persisted data to QueryCache and persists further changes.
228 * @param props - The options for both restoring and saving.
229 * @returns A tuple of a function that stops persisting, and a promise that resolves once the
230 * restore is done.
231 */
232export function persistQueryClient(
233 props: PersistQueryClientOptions,
234): [() => void, Promise<void>] {
235 let hasUnsubscribed = false
236 let persistQueryClientUnsubscribe: (() => void) | undefined
237 const unsubscribe = () => {
238 hasUnsubscribed = true
239 persistQueryClientUnsubscribe?.()
240 }
241β
242 // Attempt restore
243 const restorePromise = persistQueryClientRestore(props).then(() => {
244 if (!hasUnsubscribed) {
245 // Subscribe to changes in the query cache to trigger the save
246 persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)
247 }
248 })
249β
250 return [unsubscribe, restorePromise]
251}