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

createPersister.ts

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