Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.ts

116 lines2.9 KB

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