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

index.ts

105 lines2.7 KB

1import type {
2 PersistedClient,
3 Persister,
4 Promisable,
5} from '@tanstack/query-persist-client-core'
6import { asyncThrottle } from './asyncThrottle'
7​
8interface AsyncStorage {
9 getItem: (key: string) => Promise<string | null>
10 setItem: (key: string, value: string) => Promise<void>
11 removeItem: (key: string) => Promise<void>
13​
14export type AsyncPersistRetryer = (props: {
15 persistedClient: PersistedClient
16 error: Error
17 errorCount: number
18}) => Promisable<PersistedClient | undefined>
19​
20interface CreateAsyncStoragePersisterOptions {
21 /** The storage client used for setting and retrieving items from cache.
22 * For SSR pass in `undefined`.
23 */
24 storage: AsyncStorage | undefined
25 /** The key to use when storing the cache */
26 key?: string
27 /** To avoid spamming,
28 * pass a time in ms to throttle saving the cache to disk */
29 throttleTime?: number
30 /**
31 * How to serialize the data to storage.
32 * @default `JSON.stringify`
33 */
34 serialize?: (client: PersistedClient) => string
35 /**
36 * How to deserialize the data from storage.
37 * @default `JSON.parse`
38 */
39 deserialize?: (cachedString: string) => PersistedClient
40​
41 retry?: AsyncPersistRetryer
43​
44export const createAsyncStoragePersister = ({
45 storage,
46 key = `REACT_QUERY_OFFLINE_CACHE`,
47 throttleTime = 1000,
48 serialize = JSON.stringify,
49 deserialize = JSON.parse,
50 retry,
51}: CreateAsyncStoragePersisterOptions): Persister => {
52 if (typeof storage !== 'undefined') {
53 const trySave = async (
54 persistedClient: PersistedClient,
55 ): Promise<Error | undefined> => {
56 try {
57 await storage.setItem(key, serialize(persistedClient))
58 } catch (error) {
59 return error as Error
60 }
61 }
62​
63 return {
64 persistClient: asyncThrottle(
65 async (persistedClient) => {
66 let client: PersistedClient | undefined = persistedClient
67 let error = await trySave(client)
68 let errorCount = 0
69 while (error && client) {
70 errorCount++
71 client = await retry?.({
72 persistedClient: client,
73 error,
74 errorCount,
75 })
76​
77 if (client) {
78 error = await trySave(client)
79 }
80 }
81 },
82 { interval: throttleTime },
83 ),
84 restoreClient: async () => {
85 const cacheString = await storage.getItem(key)
86​
87 if (!cacheString) {
88 return
89 }
90​
91 return deserialize(cacheString) as PersistedClient
92 },
93 removeClient: () => storage.removeItem(key),
94 }
95 }
96​
97 return {
98 persistClient: noop,
99 restoreClient: () => Promise.resolve(undefined),
100 removeClient: noop,
101 }
103​
104// eslint-disable-next-line @typescript-eslint/no-empty-function
105function noop() {}