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

index.ts

106 lines2.7 KB

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