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