Open History to see the last commit
1import {
2 hashKey,
3 matchQuery,
4 notifyManager,
5 partialMatchKey,
6} from '@tanstack/query-core'
7import type {
8 Query,
9 QueryClient,
10 QueryFilters,
11 QueryFunctionContext,
12 QueryKey,
13 QueryState,
14} from '@tanstack/query-core'
15β
16/**
17 * A single query as stored by {@link experimental_createQueryPersister}.
18 */
19export interface PersistedQuery {
20 /**
21 * The `buster` the query was saved with. Entries with a different `buster` are discarded.
22 */
23 buster: string
24 /**
25 * The hash of the query.
26 */
27 queryHash: string
28 /**
29 * The key of the query.
30 */
31 queryKey: QueryKey
32 /**
33 * The state of the query, including its data and when it was last updated.
34 */
35 state: QueryState
36}
37β
38/**
39 * A value, or a promise that resolves to it.
40 */
41export type MaybePromise<T> = T | Promise<T>
42β
43/**
44 * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous
45 * or return promises.
46 */
47export interface AsyncStorage<TStorageValue = string> {
48 /**
49 * Reads the value stored under `key`, or `null`/`undefined` if there is none.
50 */
51 getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>
52 /**
53 * Stores `value` under `key`.
54 */
55 setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>
56 /**
57 * Removes the value stored under `key`.
58 */
59 removeItem: (key: string) => MaybePromise<void>
60 /**
61 * Returns all stored key-value pairs. Required for removing expired entries in bulk.
62 */
63 entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>
64}
65β
66/**
67 * Options for {@link experimental_createQueryPersister}.
68 */
69export interface StoragePersisterOptions<TStorageValue = string> {
70 /**
71 * The storage client used for setting and retrieving items from cache.
72 * For SSR pass in `undefined`.
73 */
74 storage: AsyncStorage<TStorageValue> | undefined | null
75 /**
76 * How to serialize the data to storage.
77 * @default `JSON.stringify`
78 */
79 serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>
80 /**
81 * How to deserialize the data from storage.
82 * @default `JSON.parse`
83 */
84 deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>
85 /**
86 * A unique string that can be used to forcefully invalidate existing caches,
87 * if they do not share the same buster string
88 */
89 buster?: string
90 /**
91 * The max-allowed age of the cache in milliseconds.
92 * If a persisted cache is found that is older than this
93 * time, it will be discarded
94 * @default 24 hours
95 */
96 maxAge?: number
97 /**
98 * Prefix to be used for storage key.
99 * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
100 * @default 'tanstack-query'
101 */
102 prefix?: string
103 /**
104 * If set to `true`, the query will refetch on successful query restoration if the data is stale.
105 * If set to `false`, the query will not refetch on successful query restoration.
106 * If set to `'always'`, the query will always refetch on successful query restoration.
107 * @defaultValue true
108 */
109 refetchOnRestore?: boolean | 'always'
110 /**
111 * Filters to narrow down which Queries should be persisted.
112 */
113 filters?: QueryFilters
114}
115β
116export const PERSISTER_KEY_PREFIX = 'tanstack-query'
117β
118/**
119 * Warning: experimental feature.
120 * This utility function enables fine-grained query persistence.
121 * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.
122 *
123 * ```
124 * useQuery({
125 * queryKey: ['myKey'],
126 * queryFn: fetcher,
127 * persister: createPersister({
128 * storage: localStorage,
129 * }),
130 * })
131 * ```
132 * @param options - The storage to persist to, and the options for serializing, expiring, and
133 * filtering persisted queries.
134 * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
135 * restore, remove, and garbage collect persisted queries manually.
136 */
137export function experimental_createQueryPersister<TStorageValue = string>({
138 storage,
139 buster = '',
140 maxAge = 1000 * 60 * 60 * 24,
141 serialize = JSON.stringify as Required<
142 StoragePersisterOptions<TStorageValue>
143 >['serialize'],
144 deserialize = JSON.parse as Required<
145 StoragePersisterOptions<TStorageValue>
146 >['deserialize'],
147 prefix = PERSISTER_KEY_PREFIX,
148 refetchOnRestore = true,
149 filters,
150}: StoragePersisterOptions<TStorageValue>) {
151 /**
152 * Checks whether a persisted query should be discarded.
153 * @param persistedQuery - The persisted query to check.
154 * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different
155 * `buster`.
156 */
157 function isExpiredOrBusted(persistedQuery: PersistedQuery) {
158 if (persistedQuery.state.dataUpdatedAt) {
159 const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt
160 const expired = queryAge > maxAge
161 const busted = persistedQuery.buster !== buster
162β
163 if (expired || busted) {
164 return true
165 }
166β
167 return false
168 }
169β
170 return true
171 }
172β
173 /**
174 * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are
175 * removed instead.
176 * @param queryHash - The hash of the query to read.
177 * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.
178 * @returns A promise that resolves with the persisted data, or `undefined` if nothing was
179 * restored.
180 */
181 async function retrieveQuery<T>(
182 queryHash: string,
183 afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,
184 ) {
185 if (storage != null) {
186 const storageKey = `${prefix}-${queryHash}`
187 try {
188 const storedData = await storage.getItem(storageKey)
189 if (storedData != null) {
190 let persistedQuery: PersistedQuery
191 try {
192 persistedQuery = await deserialize(storedData)
193 } catch {
194 await storage.removeItem(storageKey)
195 return
196 }
197β
198 if (isExpiredOrBusted(persistedQuery)) {
199 await storage.removeItem(storageKey)
200 } else {
201 if (afterRestoreMacroTask) {
202 // Just after restoring we want to get fresh data from the server if it's stale
203 notifyManager.schedule(() =>
204 afterRestoreMacroTask(persistedQuery),
205 )
206 }
207 // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves
208 return persistedQuery.state.data as T
209 }
210 }
211 } catch (err) {
212 if (process.env.NODE_ENV === 'development') {
213 console.error(err)
214 console.warn(
215 'Encountered an error attempting to restore query cache from persisted location.',
216 )
217 }
218 await storage.removeItem(storageKey)
219 }
220 }
221β
222 return
223 }
224β
225 /**
226 * Persists the query with the given key, if it exists in the client's cache.
227 * @param queryKey - The key of the query to persist.
228 * @param queryClient - The client whose cache holds the query.
229 * @returns A promise that resolves once the query is persisted.
230 */
231 async function persistQueryByKey(
232 queryKey: QueryKey,
233 queryClient: QueryClient,
234 ) {
235 if (storage != null) {
236 const query = queryClient.getQueryCache().find({ queryKey })
237 if (query) {
238 await persistQuery(query)
239 } else {
240 if (process.env.NODE_ENV === 'development') {
241 console.warn(
242 'Could not find query to be persisted. QueryKey:',
243 JSON.stringify(queryKey),
244 )
245 }
246 }
247 }
248 }
249β
250 /**
251 * Writes a query's state, key, hash, and `buster` to storage.
252 * @param query - The query to persist.
253 * @returns A promise that resolves once the entry is serialized and written.
254 */
255 async function persistQuery(query: Query) {
256 if (storage != null) {
257 const storageKey = `${prefix}-${query.queryHash}`
258 await storage.setItem(
259 storageKey,
260 await serialize({
261 state: query.state,
262 queryKey: query.queryKey,
263 queryHash: query.queryHash,
264 buster: buster,
265 }),
266 )
267 }
268 }
269β
270 /**
271 * The `persister` of a query: restores its data from storage if the query has none yet, otherwise
272 * runs `queryFn` and persists the result.
273 * @param queryFn - The query's own query function.
274 * @param ctx - The context passed to `queryFn`.
275 * @param query - The query being fetched.
276 * @returns A promise that resolves with the restored or fetched data.
277 */
278 async function persisterFn<T, TQueryKey extends QueryKey>(
279 queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,
280 ctx: QueryFunctionContext<TQueryKey>,
281 query: Query,
282 ) {
283 const matchesFilter = filters ? matchQuery(filters, query) : true
284β
285 // Try to restore only if we do not have any data in the cache and we have persister defined
286 if (matchesFilter && query.state.data === undefined && storage != null) {
287 const restoredData = await retrieveQuery(
288 query.queryHash,
289 (persistedQuery: PersistedQuery) => {
290 // Set proper updatedAt, since resolving in the first pass overrides those values
291 query.setState({
292 dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
293 errorUpdatedAt: persistedQuery.state.errorUpdatedAt,
294 })
295β
296 if (
297 refetchOnRestore === 'always' ||
298 (refetchOnRestore === true && query.isStale())
299 ) {
300 query.fetch()
301 }
302 },
303 )
304β
305 if (restoredData !== undefined) {
306 return Promise.resolve(restoredData as T)
307 }
308 }
309β
310 // If we did not restore, or restoration failed - fetch
311 const queryFnResult = await queryFn(ctx)
312β
313 if (matchesFilter && storage != null) {
314 // Persist if we have storage defined, we use timeout to get proper state to be persisted
315 notifyManager.schedule(() => {
316 persistQuery(query)
317 })
318 }
319β
320 return Promise.resolve(queryFnResult)
321 }
322β
323 /**
324 * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement
325 * `entries`.
326 * @returns A promise that resolves once every entry is checked.
327 */
328 async function persisterGc() {
329 if (storage?.entries) {
330 const storageKeyPrefix = `${prefix}-`
331 const entries = await storage.entries()
332 for (const [key, value] of entries) {
333 if (key.startsWith(storageKeyPrefix)) {
334 let persistedQuery: PersistedQuery
335 try {
336 persistedQuery = await deserialize(value)
337 } catch {
338 await storage.removeItem(key)
339 continue
340 }
341 if (isExpiredOrBusted(persistedQuery)) {
342 await storage.removeItem(key)
343 }
344 }
345 }
346 } else if (process.env.NODE_ENV === 'development') {
347 throw new Error(
348 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',
349 )
350 }
351 }
352β
353 /**
354 * Restores every persisted query matching `filters` into the client's cache with
355 * `queryClient.setQueryData`. Requires the storage to implement `entries`.
356 * @param queryClient - The client to restore the queries into.
357 * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is
358 * restored.
359 * @returns A promise that resolves once every entry is checked.
360 */
361 async function restoreQueries(
362 queryClient: QueryClient,
363 filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},
364 ): Promise<void> {
365 const { exact, queryKey } = filters
366β
367 if (storage?.entries) {
368 const storageKeyPrefix = `${prefix}-`
369 const entries = await storage.entries()
370 for (const [key, value] of entries) {
371 if (key.startsWith(storageKeyPrefix)) {
372 let persistedQuery: PersistedQuery
373 try {
374 persistedQuery = await deserialize(value)
375 } catch {
376 await storage.removeItem(key)
377 continue
378 }
379 if (isExpiredOrBusted(persistedQuery)) {
380 await storage.removeItem(key)
381 continue
382 }
383β
384 if (queryKey) {
385 if (exact) {
386 if (persistedQuery.queryHash !== hashKey(queryKey)) {
387 continue
388 }
389 } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {
390 continue
391 }
392 }
393β
394 queryClient.setQueryData(
395 persistedQuery.queryKey,
396 persistedQuery.state.data,
397 {
398 updatedAt: persistedQuery.state.dataUpdatedAt,
399 },
400 )
401 }
402 }
403 } else if (process.env.NODE_ENV === 'development') {
404 throw new Error(
405 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',
406 )
407 }
408 }
409β
410 /**
411 * Removes every persisted query matching `filters` from storage. Requires the storage to implement
412 * `entries`.
413 * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is
414 * removed.
415 * @returns A promise that resolves once every entry is checked.
416 */
417 async function removeQueries(
418 filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},
419 ): Promise<void> {
420 const { exact, queryKey } = filters
421β
422 if (storage?.entries) {
423 const entries = await storage.entries()
424 const storageKeyPrefix = `${prefix}-`
425 for (const [key, value] of entries) {
426 if (key.startsWith(storageKeyPrefix)) {
427 if (!queryKey) {
428 await storage.removeItem(key)
429 continue
430 }
431β
432 let persistedQuery: PersistedQuery
433 try {
434 persistedQuery = await deserialize(value)
435 } catch {
436 await storage.removeItem(key)
437 continue
438 }
439β
440 if (exact) {
441 if (persistedQuery.queryHash !== hashKey(queryKey)) {
442 continue
443 }
444 } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {
445 continue
446 }
447β
448 await storage.removeItem(key)
449 }
450 }
451 } else if (process.env.NODE_ENV === 'development') {
452 throw new Error(
453 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',
454 )
455 }
456 }
457β
458 return {
459 persisterFn,
460 persistQuery,
461 persistQueryByKey,
462 retrieveQuery,
463 persisterGc,
464 restoreQueries,
465 removeQueries,
466 }
467}