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

index.ts

118 lines3.3 KB

1import { asyncThrottle } from './asyncThrottle'
2import { noop } from './utils'
3import type {
4 AsyncStorage,
5 MaybePromise,
6 PersistedClient,
7 Persister,
8 Promisable,
9} from '@tanstack/query-persist-client-core'
10​
11/**
12 * Called when saving the persisted client fails. Returns, or resolves to, a
13 * smaller client to try saving again, or `undefined` to give up.
14 */
15export type AsyncPersistRetryer = (props: {
16 persistedClient: PersistedClient
17 error: Error
18 errorCount: number
19}) => Promisable<PersistedClient | undefined>
20​
21interface CreateAsyncStoragePersisterOptions {
22 /**
23 * The storage client used for setting and retrieving items from cache. For
24 * SSR pass in `undefined`. Note that window.localStorage can be `null` in
25 * Android WebViews depending on how they are configured.
26 */
27 storage: AsyncStorage<string> | undefined | null
28 /** The key to use when storing the cache */
29 key?: string
30 /** To avoid spamming, pass a time in ms to throttle saving the cache to disk */
31 throttleTime?: number
32 /**
33 * How to serialize the data to storage.
34 *
35 * @default `JSON.stringify`
36 */
37 serialize?: (client: PersistedClient) => MaybePromise<string>
38 /**
39 * How to deserialize the data from storage.
40 *
41 * @default `JSON.parse`
42 */
43 deserialize?: (cachedString: string) => MaybePromise<PersistedClient>
44​
45 retry?: AsyncPersistRetryer
47​
48/**
49 * Creates a persister that saves the client to an asynchronous storage such as
50 * `AsyncStorage`, throttled by `throttleTime`. If saving fails, `retry` can
51 * return a smaller client to try again.
52 *
53 * @param options - The `storage` to persist to, the `key`, `throttleTime`,
54 * `serialize`, `deserialize`, and `retry` options.
55 * @returns A persister that saves, restores, and removes the client in
56 * `storage`. Without `storage`, its methods do nothing.
57 */
58export const createAsyncStoragePersister = ({
59 storage,
60 key = `REACT_QUERY_OFFLINE_CACHE`,
61 throttleTime = 1000,
62 serialize = JSON.stringify,
63 deserialize = JSON.parse,
64 retry,
65}: CreateAsyncStoragePersisterOptions): Persister => {
66 if (storage) {
67 const trySave = async (
68 persistedClient: PersistedClient,
69 ): Promise<Error | undefined> => {
70 try {
71 const serialized = await serialize(persistedClient)
72 await storage.setItem(key, serialized)
73 return
74 } catch (error) {
75 return error as Error
76 }
77 }
78​
79 return {
80 persistClient: asyncThrottle(
81 async (persistedClient) => {
82 let client: PersistedClient | undefined = persistedClient
83 let error = await trySave(client)
84 let errorCount = 0
85 while (error && client) {
86 errorCount++
87 client = await retry?.({
88 persistedClient: client,
89 error,
90 errorCount,
91 })
92​
93 if (client) {
94 error = await trySave(client)
95 }
96 }
97 },
98 { interval: throttleTime },
99 ),
100 restoreClient: async () => {
101 const cacheString = await storage.getItem(key)
102​
103 if (!cacheString) {
104 return
105 }
106​
107 return await deserialize(cacheString)
108 },
109 removeClient: () => storage.removeItem(key),
110 }
111 }
112​
113 return {
114 persistClient: noop,
115 restoreClient: () => Promise.resolve(undefined),
116 removeClient: noop,
117 }