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

index.ts

102 lines2.6 KB

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