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

index.ts

107 lines2.8 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<unknown>
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`. Note that window.localStorage can be
23 * `null` in Android WebViews depending on how they are configured.
24 */
25 storage: AsyncStorage | undefined | null
26 /** The key to use when storing the cache */
27 key?: string
28 /** To avoid spamming,
29 * pass a time in ms to throttle saving the cache to disk */
30 throttleTime?: number
31 /**
32 * How to serialize the data to storage.
33 * @default `JSON.stringify`
34 */
35 serialize?: (client: PersistedClient) => string
36 /**
37 * How to deserialize the data from storage.
38 * @default `JSON.parse`
39 */
40 deserialize?: (cachedString: string) => PersistedClient
41​
42 retry?: AsyncPersistRetryer
44​
45export const createAsyncStoragePersister = ({
46 storage,
47 key = `REACT_QUERY_OFFLINE_CACHE`,
48 throttleTime = 1000,
49 serialize = JSON.stringify,
50 deserialize = JSON.parse,
51 retry,
52}: CreateAsyncStoragePersisterOptions): Persister => {
53 if (storage) {
54 const trySave = async (
55 persistedClient: PersistedClient,
56 ): Promise<Error | undefined> => {
57 try {
58 await storage.setItem(key, serialize(persistedClient))
59 return
60 } catch (error) {
61 return error as Error
62 }
63 }
64​
65 return {
66 persistClient: asyncThrottle(
67 async (persistedClient) => {
68 let client: PersistedClient | undefined = persistedClient
69 let error = await trySave(client)
70 let errorCount = 0
71 while (error && client) {
72 errorCount++
73 client = await retry?.({
74 persistedClient: client,
75 error,
76 errorCount,
77 })
78​
79 if (client) {
80 error = await trySave(client)
81 }
82 }
83 },
84 { interval: throttleTime },
85 ),
86 restoreClient: async () => {
87 const cacheString = await storage.getItem(key)
88​
89 if (!cacheString) {
90 return
91 }
92​
93 return deserialize(cacheString)
94 },
95 removeClient: () => storage.removeItem(key),
96 }
97 }
98​
99 return {
100 persistClient: noop,
101 restoreClient: () => Promise.resolve(undefined),
102 removeClient: noop,
103 }
105​
106// eslint-disable-next-line @typescript-eslint/no-empty-function
107function noop() {}