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

index.ts

92 lines2.6 KB

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 * How to serialize the data to storage.
19 * @default `JSON.stringify`
20 */
21 serialize?: (client: PersistedClient) => string
22 /**
23 * How to deserialize the data from storage.
24 * @default `JSON.parse`
25 */
26 deserialize?: (cachedString: string) => PersistedClient
28​
29export const createAsyncStoragePersistor = ({
30 storage,
31 key = `REACT_QUERY_OFFLINE_CACHE`,
32 throttleTime = 1000,
33 serialize = JSON.stringify,
34 deserialize = JSON.parse,
35}: CreateAsyncStoragePersistorOptions): Persistor => {
36 return {
37 persistClient: asyncThrottle(
38 persistedClient => storage.setItem(key, serialize(persistedClient)),
39 { interval: throttleTime }
40 ),
41 restoreClient: async () => {
42 const cacheString = await storage.getItem(key)
43​
44 if (!cacheString) {
45 return
46 }
47​
48 return deserialize(cacheString) as PersistedClient
49 },
50 removeClient: () => storage.removeItem(key),
51 }
53​
54function asyncThrottle<Args extends readonly unknown[], Result>(
55 func: (...args: Args) => Promise<Result>,
56 { interval = 1000, limit = 1 }: { interval?: number; limit?: number } = {}
57) {
58 if (typeof func !== 'function') throw new Error('argument is not function.')
59 const running = { current: false }
60 let lastTime = 0
61 let timeout: number
62 const queue: Array<Args> = []
63 return (...args: Args) =>
64 (async () => {
65 if (running.current) {
66 lastTime = Date.now()
67 if (queue.length > limit) {
68 queue.shift()
69 }
70​
71 queue.push(args)
72 clearTimeout(timeout)
73 }
74 if (Date.now() - lastTime > interval) {
75 running.current = true
76 await func(...args)
77 lastTime = Date.now()
78 running.current = false
79 } else {
80 if (queue.length > 0) {
81 const lastArgs = queue[queue.length - 1]!
82 timeout = setTimeout(async () => {
83 if (!running.current) {
84 running.current = true
85 await func(...lastArgs)
86 running.current = false
87 }
88 }, interval)
89 }
90 }
91 })()