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

index.ts

104 lines2.7 KB

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