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 } catch (error) {
50 return error as Error
51 }
52 }
53 return {
54 persistClient: throttle((persistedClient) => {
55 let client: PersistedClient | undefined = persistedClient
56 let error = trySave(client)
57 let errorCount = 0
58 while (error && client) {
59 errorCount++
60 client = retry?.({
61 persistedClient: client,
62 error,
63 errorCount,
64 })
65β
66 if (client) {
67 error = trySave(client)
68 }
69 }
70 }, throttleTime),
71 restoreClient: () => {
72 const cacheString = storage.getItem(key)
73β
74 if (!cacheString) {
75 return
76 }
77β
78 return deserialize(cacheString) as PersistedClient
79 },
80 removeClient: () => {
81 storage.removeItem(key)
82 },
83 }
84 }
85β
86 return {
87 persistClient: noop,
88 restoreClient: () => undefined,
89 removeClient: noop,
90 }
91}
92β
93function throttle<TArgs extends any[]>(
94 func: (...args: TArgs) => any,
95 wait = 100,
96) {
97 let timer: ReturnType<typeof setTimeout> | null = null
98 let params: TArgs
99 return function (...args: TArgs) {
100 params = args
101 if (timer === null) {
102 timer = setTimeout(() => {
103 func(...params)
104 timer = null
105 }, wait)
106 }
107 }
108}
109β
110// eslint-disable-next-line @typescript-eslint/no-empty-function
111function noop() {}