Open History to see the last commit
1import { PersistedClient, Persistor } from '../persistQueryClient-experimental'
2β
3interface AsyncStorage {
4 getItem: (key: string) => Promise<string | null>
5 setItem: (key: string, value: string) => Promise<void>
6 removeItem: (key: string) => Promise<void>
7}
8β
9interface CreateAsyncStoragePersistorOptions {
10 /** The storage client used for setting an retrieving items from cache */
11 storage: AsyncStorage
12 /** The key to use when storing the cache */
13 key?: string
14 /** To avoid spamming,
15 * pass a time in ms to throttle saving the cache to disk */
16 throttleTime?: number
17}
18β
19export const createAsyncStoragePersistor = ({
20 storage,
21 key = `REACT_QUERY_OFFLINE_CACHE`,
22 throttleTime = 1000,
23}: CreateAsyncStoragePersistorOptions): Persistor => {
24 return {
25 persistClient: asyncThrottle(
26 persistedClient => storage.setItem(key, JSON.stringify(persistedClient)),
27 { interval: throttleTime }
28 ),
29 restoreClient: async () => {
30 const cacheString = await storage.getItem(key)
31β
32 if (!cacheString) {
33 return
34 }
35β
36 return JSON.parse(cacheString) as PersistedClient
37 },
38 removeClient: () => storage.removeItem(key),
39 }
40}
41β
42function asyncThrottle<T>(
43 func: (...args: ReadonlyArray<unknown>) => Promise<T>,
44 { interval = 1000, limit = 1 }: { interval?: number; limit?: number } = {}
45) {
46 if (typeof func !== 'function') throw new Error('argument is not function.')
47 const running = { current: false }
48 let lastTime = 0
49 let timeout: number
50 const queue: Array<any[]> = []
51 return (...args: any) =>
52 (async () => {
53 if (running.current) {
54 lastTime = Date.now()
55 if (queue.length > limit) {
56 queue.shift()
57 }
58β
59 queue.push(args)
60 clearTimeout(timeout)
61 }
62 if (Date.now() - lastTime > interval) {
63 running.current = true
64 await func(...args)
65 lastTime = Date.now()
66 running.current = false
67 } else {
68 if (queue.length > 0) {
69 const lastArgs = queue[queue.length - 1]!
70 timeout = setTimeout(async () => {
71 if (!running.current) {
72 running.current = true
73 await func(...lastArgs)
74 running.current = false
75 }
76 }, interval)
77 }
78 }
79 })()
80}