Open History to see the last commit
1import {
2 hashKey,
3 matchQuery,
4 notifyManager,
5 partialMatchKey,
6} from '@tanstack/query-core'
7import type {
8 Query,
9 QueryClient,
10 QueryFilters,
11 QueryFunctionContext,
12 QueryKey,
13 QueryState,
14} from '@tanstack/query-core'
15β
16export interface PersistedQuery {
17 buster: string
18 queryHash: string
19 queryKey: QueryKey
20 state: QueryState
21}
22β
23export type MaybePromise<T> = T | Promise<T>
24β
25export interface AsyncStorage<TStorageValue = string> {
26 getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>
27 setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>
28 removeItem: (key: string) => MaybePromise<void>
29 entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>
30}
31β
32export interface StoragePersisterOptions<TStorageValue = string> {
33 /** The storage client used for setting and retrieving items from cache.
34 * For SSR pass in `undefined`.
35 */
36 storage: AsyncStorage<TStorageValue> | undefined | null
37 /**
38 * How to serialize the data to storage.
39 * @default `JSON.stringify`
40 */
41 serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>
42 /**
43 * How to deserialize the data from storage.
44 * @default `JSON.parse`
45 */
46 deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>
47 /**
48 * A unique string that can be used to forcefully invalidate existing caches,
49 * if they do not share the same buster string
50 */
51 buster?: string
52 /**
53 * The max-allowed age of the cache in milliseconds.
54 * If a persisted cache is found that is older than this
55 * time, it will be discarded
56 * @default 24 hours
57 */
58 maxAge?: number
59 /**
60 * Prefix to be used for storage key.
61 * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
62 * @default 'tanstack-query'
63 */
64 prefix?: string
65 /**
66 * If set to `true`, the query will refetch on successful query restoration if the data is stale.
67 * If set to `false`, the query will not refetch on successful query restoration.
68 * If set to `'always'`, the query will always refetch on successful query restoration.
69 * Defaults to `true`.
70 */
71 refetchOnRestore?: boolean | 'always'
72 /**
73 * Filters to narrow down which Queries should be persisted.
74 */
75 filters?: QueryFilters
76}
77β
78export const PERSISTER_KEY_PREFIX = 'tanstack-query'
79β
80/**
81 * Warning: experimental feature.
82 * This utility function enables fine-grained query persistence.
83 * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.
84 *
85 * ```
86 * useQuery({
87 queryKey: ['myKey'],
88 queryFn: fetcher,
89 persister: createPersister({
90 storage: localStorage,
91 }),
92 })
93 ```
94 */
95export function experimental_createQueryPersister<TStorageValue = string>({
96 storage,
97 buster = '',
98 maxAge = 1000 * 60 * 60 * 24,
99 serialize = JSON.stringify as Required<
100 StoragePersisterOptions<TStorageValue>
101 >['serialize'],
102 deserialize = JSON.parse as Required<
103 StoragePersisterOptions<TStorageValue>
104 >['deserialize'],
105 prefix = PERSISTER_KEY_PREFIX,
106 refetchOnRestore = true,
107 filters,
108}: StoragePersisterOptions<TStorageValue>) {
109 function isExpiredOrBusted(persistedQuery: PersistedQuery) {
110 if (persistedQuery.state.dataUpdatedAt) {
111 const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt
112 const expired = queryAge > maxAge
113 const busted = persistedQuery.buster !== buster
114β
115 if (expired || busted) {
116 return true
117 }
118β
119 return false
120 }
121β
122 return true
123 }
124β
125 async function retrieveQuery<T>(
126 queryHash: string,
127 afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,
128 ) {
129 if (storage != null) {
130 const storageKey = `${prefix}-${queryHash}`
131 try {
132 const storedData = await storage.getItem(storageKey)
133 if (storedData) {
134 let persistedQuery: PersistedQuery
135 try {
136 persistedQuery = await deserialize(storedData)
137 } catch {
138 await storage.removeItem(storageKey)
139 return
140 }
141β
142 if (isExpiredOrBusted(persistedQuery)) {
143 await storage.removeItem(storageKey)
144 } else {
145 if (afterRestoreMacroTask) {
146 // Just after restoring we want to get fresh data from the server if it's stale
147 notifyManager.schedule(() =>
148 afterRestoreMacroTask(persistedQuery),
149 )
150 }
151 // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves
152 return persistedQuery.state.data as T
153 }
154 }
155 } catch (err) {
156 if (process.env.NODE_ENV === 'development') {
157 console.error(err)
158 console.warn(
159 'Encountered an error attempting to restore query cache from persisted location.',
160 )
161 }
162 await storage.removeItem(storageKey)
163 }
164 }
165β
166 return
167 }
168β
169 async function persistQueryByKey(
170 queryKey: QueryKey,
171 queryClient: QueryClient,
172 ) {
173 if (storage != null) {
174 const query = queryClient.getQueryCache().find({ queryKey })
175 if (query) {
176 await persistQuery(query)
177 } else {
178 if (process.env.NODE_ENV === 'development') {
179 console.warn(
180 'Could not find query to be persisted. QueryKey:',
181 JSON.stringify(queryKey),
182 )
183 }
184 }
185 }
186 }
187β
188 async function persistQuery(query: Query) {
189 if (storage != null) {
190 const storageKey = `${prefix}-${query.queryHash}`
191 storage.setItem(
192 storageKey,
193 await serialize({
194 state: query.state,
195 queryKey: query.queryKey,
196 queryHash: query.queryHash,
197 buster: buster,
198 }),
199 )
200 }
201 }
202β
203 async function persisterFn<T, TQueryKey extends QueryKey>(
204 queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,
205 ctx: QueryFunctionContext<TQueryKey>,
206 query: Query,
207 ) {
208 const matchesFilter = filters ? matchQuery(filters, query) : true
209β
210 // Try to restore only if we do not have any data in the cache and we have persister defined
211 if (matchesFilter && query.state.data === undefined && storage != null) {
212 const restoredData = await retrieveQuery(
213 query.queryHash,
214 (persistedQuery: PersistedQuery) => {
215 // Set proper updatedAt, since resolving in the first pass overrides those values
216 query.setState({
217 dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
218 errorUpdatedAt: persistedQuery.state.errorUpdatedAt,
219 })
220β
221 if (
222 refetchOnRestore === 'always' ||
223 (refetchOnRestore === true && query.isStale())
224 ) {
225 query.fetch()
226 }
227 },
228 )
229β
230 if (restoredData !== undefined) {
231 return Promise.resolve(restoredData as T)
232 }
233 }
234β
235 // If we did not restore, or restoration failed - fetch
236 const queryFnResult = await queryFn(ctx)
237β
238 if (matchesFilter && storage != null) {
239 // Persist if we have storage defined, we use timeout to get proper state to be persisted
240 notifyManager.schedule(() => {
241 persistQuery(query)
242 })
243 }
244β
245 return Promise.resolve(queryFnResult)
246 }
247β
248 async function persisterGc() {
249 if (storage?.entries) {
250 const storageKeyPrefix = `${prefix}-`
251 const entries = await storage.entries()
252 for (const [key, value] of entries) {
253 if (key.startsWith(storageKeyPrefix)) {
254 let persistedQuery: PersistedQuery
255 try {
256 persistedQuery = await deserialize(value)
257 } catch {
258 await storage.removeItem(key)
259 continue
260 }
261 if (isExpiredOrBusted(persistedQuery)) {
262 await storage.removeItem(key)
263 }
264 }
265 }
266 } else if (process.env.NODE_ENV === 'development') {
267 throw new Error(
268 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',
269 )
270 }
271 }
272β
273 async function restoreQueries(
274 queryClient: QueryClient,
275 filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},
276 ): Promise<void> {
277 const { exact, queryKey } = filters
278β
279 if (storage?.entries) {
280 const storageKeyPrefix = `${prefix}-`
281 const entries = await storage.entries()
282 for (const [key, value] of entries) {
283 if (key.startsWith(storageKeyPrefix)) {
284 let persistedQuery: PersistedQuery
285 try {
286 persistedQuery = await deserialize(value)
287 } catch {
288 await storage.removeItem(key)
289 continue
290 }
291 if (isExpiredOrBusted(persistedQuery)) {
292 await storage.removeItem(key)
293 continue
294 }
295β
296 if (queryKey) {
297 if (exact) {
298 if (persistedQuery.queryHash !== hashKey(queryKey)) {
299 continue
300 }
301 } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {
302 continue
303 }
304 }
305β
306 queryClient.setQueryData(
307 persistedQuery.queryKey,
308 persistedQuery.state.data,
309 {
310 updatedAt: persistedQuery.state.dataUpdatedAt,
311 },
312 )
313 }
314 }
315 } else if (process.env.NODE_ENV === 'development') {
316 throw new Error(
317 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',
318 )
319 }
320 }
321β
322 async function removeQueries(
323 filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},
324 ): Promise<void> {
325 const { exact, queryKey } = filters
326β
327 if (storage?.entries) {
328 const entries = await storage.entries()
329 const storageKeyPrefix = `${prefix}-`
330 for (const [key, value] of entries) {
331 if (key.startsWith(storageKeyPrefix)) {
332 if (!queryKey) {
333 await storage.removeItem(key)
334 continue
335 }
336β
337 let persistedQuery: PersistedQuery
338 try {
339 persistedQuery = await deserialize(value)
340 } catch {
341 await storage.removeItem(key)
342 continue
343 }
344β
345 if (exact) {
346 if (persistedQuery.queryHash !== hashKey(queryKey)) {
347 continue
348 }
349 } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {
350 continue
351 }
352β
353 await storage.removeItem(key)
354 }
355 }
356 } else if (process.env.NODE_ENV === 'development') {
357 throw new Error(
358 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',
359 )
360 }
361 }
362β
363 return {
364 persisterFn,
365 persistQuery,
366 persistQueryByKey,
367 retrieveQuery,
368 persisterGc,
369 restoreQueries,
370 removeQueries,
371 }
372}