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β
11/**
12 * Called when saving the persisted client fails. Returns, or resolves to, a smaller client to try
13 * saving again, or `undefined` to give up.
14 */
15export type AsyncPersistRetryer = (props: {
16 persistedClient: PersistedClient
17 error: Error
18 errorCount: number
19}) => Promisable<PersistedClient | undefined>
20β
21interface CreateAsyncStoragePersisterOptions {
22 /**
23 * The storage client used for setting and retrieving items from cache.
24 * For SSR pass in `undefined`. Note that window.localStorage can be
25 * `null` in Android WebViews depending on how they are configured.
26 */
27 storage: AsyncStorage<string> | undefined | null
28 /** The key to use when storing the cache */
29 key?: string
30 /**
31 * To avoid spamming,
32 * pass a time in ms to throttle saving the cache to disk
33 */
34 throttleTime?: number
35 /**
36 * How to serialize the data to storage.
37 * @default `JSON.stringify`
38 */
39 serialize?: (client: PersistedClient) => MaybePromise<string>
40 /**
41 * How to deserialize the data from storage.
42 * @default `JSON.parse`
43 */
44 deserialize?: (cachedString: string) => MaybePromise<PersistedClient>
45β
46 retry?: AsyncPersistRetryer
47}
48β
49/**
50 * Creates a persister that saves the client to an asynchronous storage such as `AsyncStorage`,
51 * throttled by `throttleTime`. If saving fails, `retry` can return a smaller client to try again.
52 * @param options - The `storage` to persist to, the `key`, `throttleTime`, `serialize`,
53 * `deserialize`, and `retry` options.
54 * @returns A persister that saves, restores, and removes the client in `storage`. Without
55 * `storage`, its methods do nothing.
56 */
57export const createAsyncStoragePersister = ({
58 storage,
59 key = `REACT_QUERY_OFFLINE_CACHE`,
60 throttleTime = 1000,
61 serialize = JSON.stringify,
62 deserialize = JSON.parse,
63 retry,
64}: CreateAsyncStoragePersisterOptions): Persister => {
65 if (storage) {
66 const trySave = async (
67 persistedClient: PersistedClient,
68 ): Promise<Error | undefined> => {
69 try {
70 const serialized = await serialize(persistedClient)
71 await storage.setItem(key, serialized)
72 return
73 } catch (error) {
74 return error as Error
75 }
76 }
77β
78 return {
79 persistClient: asyncThrottle(
80 async (persistedClient) => {
81 let client: PersistedClient | undefined = persistedClient
82 let error = await trySave(client)
83 let errorCount = 0
84 while (error && client) {
85 errorCount++
86 client = await retry?.({
87 persistedClient: client,
88 error,
89 errorCount,
90 })
91β
92 if (client) {
93 error = await trySave(client)
94 }
95 }
96 },
97 { interval: throttleTime },
98 ),
99 restoreClient: async () => {
100 const cacheString = await storage.getItem(key)
101β
102 if (!cacheString) {
103 return
104 }
105β
106 return await deserialize(cacheString)
107 },
108 removeClient: () => storage.removeItem(key),
109 }
110 }
111β
112 return {
113 persistClient: noop,
114 restoreClient: () => Promise.resolve(undefined),
115 removeClient: noop,
116 }
117}