Open History to see the last commit
1import { asyncThrottle } from './asyncThrottle'
2import { noop } from './utils'
3import type {
4 AsyncStorage,
5 MaybePromise,
6 PersistedClient,
7 Persister,
8 Promisable,
9} from '@tanstack/query-persist-client-core'
10β
11export type AsyncPersistRetryer = (props: {
12 persistedClient: PersistedClient
13 error: Error
14 errorCount: number
15}) => Promisable<PersistedClient | undefined>
16β
17interface CreateAsyncStoragePersisterOptions {
18 /** The storage client used for setting and retrieving items from cache.
19 * For SSR pass in `undefined`. Note that window.localStorage can be
20 * `null` in Android WebViews depending on how they are configured.
21 */
22 storage: AsyncStorage<string> | undefined | null
23 /** The key to use when storing the cache */
24 key?: string
25 /** To avoid spamming,
26 * pass a time in ms to throttle saving the cache to disk */
27 throttleTime?: number
28 /**
29 * How to serialize the data to storage.
30 * @default `JSON.stringify`
31 */
32 serialize?: (client: PersistedClient) => MaybePromise<string>
33 /**
34 * How to deserialize the data from storage.
35 * @default `JSON.parse`
36 */
37 deserialize?: (cachedString: string) => MaybePromise<PersistedClient>
38β
39 retry?: AsyncPersistRetryer
40}
41β
42export const createAsyncStoragePersister = ({
43 storage,
44 key = `REACT_QUERY_OFFLINE_CACHE`,
45 throttleTime = 1000,
46 serialize = JSON.stringify,
47 deserialize = JSON.parse,
48 retry,
49}: CreateAsyncStoragePersisterOptions): Persister => {
50 if (storage) {
51 const trySave = async (
52 persistedClient: PersistedClient,
53 ): Promise<Error | undefined> => {
54 try {
55 const serialized = await serialize(persistedClient)
56 await storage.setItem(key, serialized)
57 return
58 } catch (error) {
59 return error as Error
60 }
61 }
62β
63 return {
64 persistClient: asyncThrottle(
65 async (persistedClient) => {
66 let client: PersistedClient | undefined = persistedClient
67 let error = await trySave(client)
68 let errorCount = 0
69 while (error && client) {
70 errorCount++
71 client = await retry?.({
72 persistedClient: client,
73 error,
74 errorCount,
75 })
76β
77 if (client) {
78 error = await trySave(client)
79 }
80 }
81 },
82 { interval: throttleTime },
83 ),
84 restoreClient: async () => {
85 const cacheString = await storage.getItem(key)
86β
87 if (!cacheString) {
88 return
89 }
90β
91 return await deserialize(cacheString)
92 },
93 removeClient: () => storage.removeItem(key),
94 }
95 }
96β
97 return {
98 persistClient: noop,
99 restoreClient: () => Promise.resolve(undefined),
100 removeClient: noop,
101 }
102}