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`.
16 */
17 storage: Storage | undefined
18 /** The key to use when storing the cache */
19 key?: string
20 /** To avoid spamming,
21 * pass a time in ms to throttle saving the cache to disk */
22 throttleTime?: number
23 /**
24 * How to serialize the data to storage.
25 * @default `JSON.stringify`
26 */
27 serialize?: (client: PersistedClient) => string
28 /**
29 * How to deserialize the data from storage.
30 * @default `JSON.parse`
31 */
32 deserialize?: (cachedString: string) => PersistedClient
33β
34 retry?: PersistRetryer
35}
36β
37export function createSyncStoragePersister({
38 storage,
39 key = `REACT_QUERY_OFFLINE_CACHE`,
40 throttleTime = 1000,
41 serialize = JSON.stringify,
42 deserialize = JSON.parse,
43 retry,
44}: CreateSyncStoragePersisterOptions): Persister {
45 if (typeof storage !== 'undefined') {
46 const trySave = (persistedClient: PersistedClient): Error | undefined => {
47 try {
48 storage.setItem(key, serialize(persistedClient))
49 return
50 } catch (error) {
51 return error as Error
52 }
53 }
54 return {
55 persistClient: throttle((persistedClient) => {
56 let client: PersistedClient | undefined = persistedClient
57 let error = trySave(client)
58 let errorCount = 0
59 while (error && client) {
60 errorCount++
61 client = retry?.({
62 persistedClient: client,
63 error,
64 errorCount,
65 })
66β
67 if (client) {
68 error = trySave(client)
69 }
70 }
71 }, throttleTime),
72 restoreClient: () => {
73 const cacheString = storage.getItem(key)
74β
75 if (!cacheString) {
76 return
77 }
78β
79 return deserialize(cacheString) as PersistedClient
80 },
81 removeClient: () => {
82 storage.removeItem(key)
83 },
84 }
85 }
86β
87 return {
88 persistClient: noop,
89 restoreClient: () => undefined,
90 removeClient: noop,
91 }
92}
93β
94function throttle<TArgs extends any[]>(
95 func: (...args: TArgs) => any,
96 wait = 100,
97) {
98 let timer: ReturnType<typeof setTimeout> | null = null
99 let params: TArgs
100 return function (...args: TArgs) {
101 params = args
102 if (timer === null) {
103 timer = setTimeout(() => {
104 func(...params)
105 timer = null
106 }, wait)
107 }
108 }
109}
110β
111// eslint-disable-next-line @typescript-eslint/no-empty-function
112function noop() {}