Open History to see the last commit
1import { noop } from '../core/utils'
2import { PersistedClient, Persistor } from '../persistQueryClient-experimental'
3β
4interface CreateWebStoragePersistorOptions {
5 /** The storage client used for setting an retrieving items from cache */
6 storage: Storage
7 /** The key to use when storing the cache */
8 key?: string
9 /** To avoid spamming,
10 * pass a time in ms to throttle saving the cache to disk */
11 throttleTime?: number
12}
13β
14export function createWebStoragePersistor({
15 storage,
16 key = `REACT_QUERY_OFFLINE_CACHE`,
17 throttleTime = 1000,
18}: CreateWebStoragePersistorOptions): Persistor {
19 if (typeof storage !== 'undefined') {
20 return {
21 persistClient: throttle(persistedClient => {
22 storage.setItem(key, JSON.stringify(persistedClient))
23 }, throttleTime),
24 restoreClient: () => {
25 const cacheString = storage.getItem(key)
26β
27 if (!cacheString) {
28 return
29 }
30β
31 return JSON.parse(cacheString) as PersistedClient
32 },
33 removeClient: () => {
34 storage.removeItem(key)
35 },
36 }
37 }
38β
39 return {
40 persistClient: noop,
41 restoreClient: noop,
42 removeClient: noop,
43 }
44}
45β
46function throttle<TArgs extends any[]>(
47 func: (...args: TArgs) => any,
48 wait = 100
49) {
50 let timer: number | null = null
51β
52 return function (...args: TArgs) {
53 if (timer === null) {
54 timer = setTimeout(() => {
55 func(...args)
56 timer = null
57 }, wait)
58 }
59 }
60}