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

createPersister.ts

506 lines15.6 KB

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
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]>>
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
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 = 24 * 60 * 60 * 1000,
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: persistFilters,
150}: StoragePersisterOptions<TStorageValue>) {
151 /**
152 * Checks the fields used to filter, expire, and restore a deserialized query.
153 * @param value - The deserialized value to check.
154 * @returns `true` if the value can be processed as a persisted query.
155 */
156 function isValidPersistedQuery(value: unknown) {
157 if (typeof value !== 'object' || value === null || Array.isArray(value)) {
158 return false
159 }
160​
161 const persistedQuery = value as Partial<Omit<PersistedQuery, 'state'>> & {
162 state?: Partial<QueryState> | null
163 }
164 const state = persistedQuery.state
165​
166 return (
167 typeof persistedQuery.queryHash === 'string' &&
168 Array.isArray(persistedQuery.queryKey) &&
169 typeof state === 'object' &&
170 state !== null &&
171 !Array.isArray(state) &&
172 Number.isFinite(state.dataUpdatedAt)
173 )
174 }
175​
176 /**
177 * Checks whether a persisted query should be discarded.
178 * @param persistedQuery - The persisted query to check.
179 * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different
180 * `buster`.
181 */
182 function isExpiredOrBusted(persistedQuery: PersistedQuery) {
183 if (persistedQuery.state.dataUpdatedAt) {
184 const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt
185 const expired = queryAge > maxAge
186 const busted = persistedQuery.buster !== buster
187​
188 if (expired || busted) {
189 return true
190 }
191​
192 return false
193 }
194​
195 return true
196 }
197​
198 /**
199 * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are
200 * removed instead.
201 * @param queryHash - The hash of the query to read.
202 * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.
203 * @returns A promise that resolves with the persisted data, or `undefined` if nothing was
204 * restored.
205 */
206 async function retrieveQuery<T>(
207 queryHash: string,
208 afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,
209 ) {
210 if (storage != null) {
211 const storageKey = `${prefix}-${queryHash}`
212 try {
213 const storedData = await storage.getItem(storageKey)
214 if (storedData != null) {
215 let persistedQuery: PersistedQuery
216 try {
217 persistedQuery = await deserialize(storedData)
218 if (!isValidPersistedQuery(persistedQuery)) {
219 throw new Error('Invalid persisted query')
220 }
221 } catch {
222 await storage.removeItem(storageKey)
223 return
224 }
225​
226 if (isExpiredOrBusted(persistedQuery)) {
227 await storage.removeItem(storageKey)
228 } else {
229 if (afterRestoreMacroTask) {
230 // Just after restoring we want to get fresh data from the server if it's stale
231 notifyManager.schedule(() =>
232 afterRestoreMacroTask(persistedQuery),
233 )
234 }
235 // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves
236 return persistedQuery.state.data as T
237 }
238 }
239 } catch (err) {
240 if (process.env.NODE_ENV === 'development') {
241 console.error(err)
242 console.warn(
243 'Encountered an error attempting to restore query cache from persisted location.',
244 )
245 }
246 await storage.removeItem(storageKey)
247 }
248 }
249​
250 return
251 }
252​
253 /**
254 * Persists the query with the given key, if it exists in the client's cache.
255 * @param queryKey - The key of the query to persist.
256 * @param queryClient - The client whose cache holds the query.
257 * @returns A promise that resolves once the query is persisted.
258 */
259 async function persistQueryByKey(
260 queryKey: QueryKey,
261 queryClient: QueryClient,
262 ) {
263 if (storage != null) {
264 const query = queryClient.getQueryCache().find({ queryKey })
265 if (query) {
266 await persistQuery(query)
267 } else {
268 if (process.env.NODE_ENV === 'development') {
269 console.warn(
270 'Could not find query to be persisted. QueryKey:',
271 JSON.stringify(queryKey),
272 )
273 }
274 }
275 }
276 }
277​
278 /**
279 * Writes a query's state, key, hash, and `buster` to storage.
280 * @param query - The query to persist.
281 * @returns A promise that resolves once the entry is serialized and written.
282 */
283 async function persistQuery(query: Query) {
284 if (storage != null) {
285 const storageKey = `${prefix}-${query.queryHash}`
286 await storage.setItem(
287 storageKey,
288 await serialize({
289 state: query.state,
290 queryKey: query.queryKey,
291 queryHash: query.queryHash,
292 buster: buster,
293 }),
294 )
295 }
296 }
297​
298 /**
299 * The `persister` of a query: restores its data from storage if the query has none yet, otherwise
300 * runs `queryFn` and persists the result.
301 * @param queryFn - The query's own query function.
302 * @param ctx - The context passed to `queryFn`.
303 * @param query - The query being fetched.
304 * @returns A promise that resolves with the restored or fetched data.
305 */
306 async function persisterFn<T, TQueryKey extends QueryKey>(
307 queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,
308 ctx: QueryFunctionContext<TQueryKey>,
309 query: Query,
310 ) {
311 const matchesFilter = persistFilters
312 ? matchQuery(persistFilters, query)
313 : true
314​
315 // Try to restore only if we do not have any data in the cache and we have persister defined
316 if (matchesFilter && query.state.data === undefined && storage != null) {
317 const restoredData = await retrieveQuery(
318 query.queryHash,
319 (persistedQuery: PersistedQuery) => {
320 // Set proper updatedAt, since resolving in the first pass overrides those values
321 query.setState({
322 dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
323 errorUpdatedAt: persistedQuery.state.errorUpdatedAt,
324 })
325​
326 if (
327 refetchOnRestore === 'always' ||
328 (refetchOnRestore === true && query.isStale())
329 ) {
330 query.fetch()
331 }
332 },
333 )
334​
335 if (restoredData !== undefined) {
336 return Promise.resolve(restoredData as T)
337 }
338 }
339​
340 // If we did not restore, or restoration failed - fetch
341 const queryFnResult = await queryFn(ctx)
342​
343 if (matchesFilter && storage != null) {
344 // Persist if we have storage defined, we use timeout to get proper state to be persisted
345 notifyManager.schedule(() => {
346 persistQuery(query)
347 })
348 }
349​
350 return Promise.resolve(queryFnResult)
351 }
352​
353 /**
354 * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement
355 * `entries`.
356 * @returns A promise that resolves once every entry is checked.
357 */
358 async function persisterGc() {
359 if (storage?.entries) {
360 const storageKeyPrefix = `${prefix}-`
361 const entries = await storage.entries()
362 for (const [key, value] of entries) {
363 if (key.startsWith(storageKeyPrefix)) {
364 let persistedQuery: PersistedQuery
365 try {
366 persistedQuery = await deserialize(value)
367 if (!isValidPersistedQuery(persistedQuery)) {
368 throw new Error('Invalid persisted query')
369 }
370 } catch {
371 await storage.removeItem(key)
372 continue
373 }
374 if (isExpiredOrBusted(persistedQuery)) {
375 await storage.removeItem(key)
376 }
377 }
378 }
379 } else if (process.env.NODE_ENV === 'development') {
380 throw new Error(
381 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',
382 )
383 }
384 }
385​
386 /**
387 * Restores every persisted query matching `filters` into the client's cache with
388 * `queryClient.setQueryData`. Requires the storage to implement `entries`.
389 * @param queryClient - The client to restore the queries into.
390 * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is
391 * restored.
392 * @returns A promise that resolves once every entry is checked.
393 */
394 async function restoreQueries(
395 queryClient: QueryClient,
396 filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},
397 ): Promise<void> {
398 const { exact, queryKey } = filters
399​
400 if (storage?.entries) {
401 const storageKeyPrefix = `${prefix}-`
402 const entries = await storage.entries()
403 for (const [key, value] of entries) {
404 if (key.startsWith(storageKeyPrefix)) {
405 let persistedQuery: PersistedQuery
406 try {
407 persistedQuery = await deserialize(value)
408 if (!isValidPersistedQuery(persistedQuery)) {
409 throw new Error('Invalid persisted query')
410 }
411 } catch {
412 await storage.removeItem(key)
413 continue
414 }
415 if (isExpiredOrBusted(persistedQuery)) {
416 await storage.removeItem(key)
417 continue
418 }
419​
420 if (queryKey) {
421 if (exact) {
422 if (persistedQuery.queryHash !== hashKey(queryKey)) {
423 continue
424 }
425 } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {
426 continue
427 }
428 }
429​
430 queryClient.setQueryData(
431 persistedQuery.queryKey,
432 persistedQuery.state.data,
433 {
434 updatedAt: persistedQuery.state.dataUpdatedAt,
435 },
436 )
437 }
438 }
439 } else if (process.env.NODE_ENV === 'development') {
440 throw new Error(
441 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',
442 )
443 }
444 }
445​
446 /**
447 * Removes every persisted query matching `filters` from storage. Requires the storage to implement
448 * `entries`.
449 * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is
450 * removed.
451 * @returns A promise that resolves once every entry is checked.
452 */
453 async function removeQueries(
454 filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},
455 ): Promise<void> {
456 const { exact, queryKey } = filters
457​
458 if (storage?.entries) {
459 const entries = await storage.entries()
460 const storageKeyPrefix = `${prefix}-`
461 for (const [key, value] of entries) {
462 if (key.startsWith(storageKeyPrefix)) {
463 if (!queryKey) {
464 await storage.removeItem(key)
465 continue
466 }
467​
468 let persistedQuery: PersistedQuery
469 try {
470 persistedQuery = await deserialize(value)
471 if (!isValidPersistedQuery(persistedQuery)) {
472 throw new Error('Invalid persisted query')
473 }
474 } catch {
475 await storage.removeItem(key)
476 continue
477 }
478​
479 if (exact) {
480 if (persistedQuery.queryHash !== hashKey(queryKey)) {
481 continue
482 }
483 } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {
484 continue
485 }
486​
487 await storage.removeItem(key)
488 }
489 }
490 } else if (process.env.NODE_ENV === 'development') {
491 throw new Error(
492 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',
493 )
494 }
495 }
496​
497 return {
498 persisterFn,
499 persistQuery,
500 persistQueryByKey,
501 retrieveQuery,
502 persisterGc,
503 restoreQueries,
504 removeQueries,
505 }