Open History to see the last commit
1import type {
2 PersistedClient,
3 Persister,
4 PersistRetryer,
5} from '@tanstack/query-persist-client-core'
6β
7interface Storage {
8 getItem: (key: string) => string | null
9 setItem: (key: string, value: string) => void
10 removeItem: (key: string) => void
11}
12β
13interface CreateSyncStoragePersisterOptions {
14 /** The storage client used for setting and retrieving items from cache.
15 * For SSR pass in `undefined`. Note that window.localStorage can be
16 * `null` in Android WebViews depending on how they are configured.
17 */
18 storage: Storage | undefined | null
19 /** The key to use when storing the cache */
20 key?: string
21 /** To avoid spamming,
22 * pass a time in ms to throttle saving the cache to disk */
23 throttleTime?: number
24 /**
25 * How to serialize the data to storage.
26 * @default `JSON.stringify`
27 */
28 serialize?: (client: PersistedClient) => string
29 /**
30 * How to deserialize the data from storage.
31 * @default `JSON.parse`
32 */
33 deserialize?: (cachedString: string) => PersistedClient
34β
35 retry?: PersistRetryer
36}
37β
38export function createSyncStoragePersister({
39 storage,
40 key = `REACT_QUERY_OFFLINE_CACHE`,
41 throttleTime = 1000,
42 serialize = JSON.stringify,
43 deserialize = JSON.parse,
44 retry,
45}: CreateSyncStoragePersisterOptions): Persister {
46 if (storage) {
47 const trySave = (persistedClient: PersistedClient): Error | undefined => {
48 try {
49 storage.setItem(key, serialize(persistedClient))
50 return
51 } catch (error) {
52 return error as Error
53 }
54 }
55 return {
56 persistClient: throttle((persistedClient) => {
57 let client: PersistedClient | undefined = persistedClient
58 let error = trySave(client)
59 let errorCount = 0
60 while (error && client) {
61 errorCount++
62 client = retry?.({
63 persistedClient: client,
64 error,
65 errorCount,
66 })
67β
68 if (client) {
69 error = trySave(client)
70 }
71 }
72 }, throttleTime),
73 restoreClient: () => {
74 const cacheString = storage.getItem(key)
75β
76 if (!cacheString) {
77 return
78 }
79β
80 return deserialize(cacheString) as PersistedClient
81 },
82 removeClient: () => {
83 storage.removeItem(key)
84 },
85 }
86 }
87β
88 return {
89 persistClient: noop,
90 restoreClient: () => undefined,
91 removeClient: noop,
92 }
93}
94β
95function throttle<TArgs extends any[]>(
96 func: (...args: TArgs) => any,
97 wait = 100,
98) {
99 let timer: ReturnType<typeof setTimeout> | null = null
100 let params: TArgs
101 return function (...args: TArgs) {
102 params = args
103 if (timer === null) {
104 timer = setTimeout(() => {
105 func(...params)
106 timer = null
107 }, wait)
108 }
109 }
110}
111β
112// eslint-disable-next-line @typescript-eslint/no-empty-function
113function noop() {}