|
|
import { hashKey, matchQuery, partialMatchKey } from '@tanstack/query-core' |
|
|
import type { |
|
|
Query, |
|
|
QueryClient, |
|
|
QueryFilters, |
|
|
QueryFunctionContext, |
|
|
QueryKey, |
|
|
QueryState, |
|
|
} from '@tanstack/query-core' |
|
|
|
|
|
export interface PersistedQuery { |
|
|
buster: string |
|
|
queryHash: string |
|
|
queryKey: QueryKey |
|
|
state: QueryState |
|
|
} |
|
|
|
|
|
export type MaybePromise<T> = T | Promise<T> |
|
|
|
|
|
export interface AsyncStorage<TStorageValue = string> { |
|
|
getItem: (key: string) => MaybePromise<TStorageValue | undefined | null> |
|
|
setItem: (key: string, value: TStorageValue) => MaybePromise<unknown> |
|
|
removeItem: (key: string) => MaybePromise<void> |
|
|
entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>> |
|
|
} |
|
|
|
|
|
export interface StoragePersisterOptions<TStorageValue = string> { |
|
|
|
|
|
|
|
|
|
|
|
storage: AsyncStorage<TStorageValue> | undefined | null |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue> |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery> |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
buster?: string |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
maxAge?: number |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
prefix?: string |
|
|
|
|
|
|
|
|
|
|
|
filters?: QueryFilters |
|
|
} |
|
|
|
|
|
export const PERSISTER_KEY_PREFIX = 'tanstack-query' |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function experimental_createQueryPersister<TStorageValue = string>({ |
|
|
storage, |
|
|
buster = '', |
|
|
maxAge = 1000 * 60 * 60 * 24, |
|
|
serialize = JSON.stringify as Required< |
|
|
StoragePersisterOptions<TStorageValue> |
|
|
>['serialize'], |
|
|
deserialize = JSON.parse as Required< |
|
|
StoragePersisterOptions<TStorageValue> |
|
|
>['deserialize'], |
|
|
prefix = PERSISTER_KEY_PREFIX, |
|
|
filters, |
|
|
}: StoragePersisterOptions<TStorageValue>) { |
|
|
function isExpiredOrBusted(persistedQuery: PersistedQuery) { |
|
|
if (persistedQuery.state.dataUpdatedAt) { |
|
|
const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt |
|
|
const expired = queryAge > maxAge |
|
|
const busted = persistedQuery.buster !== buster |
|
|
|
|
|
if (expired || busted) { |
|
|
return true |
|
|
} |
|
|
|
|
|
return false |
|
|
} |
|
|
|
|
|
return true |
|
|
} |
|
|
|
|
|
async function retrieveQuery<T>( |
|
|
queryHash: string, |
|
|
afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void, |
|
|
) { |
|
|
if (storage != null) { |
|
|
const storageKey = `${prefix}-${queryHash}` |
|
|
try { |
|
|
const storedData = await storage.getItem(storageKey) |
|
|
if (storedData) { |
|
|
const persistedQuery = await deserialize(storedData) |
|
|
|
|
|
if (isExpiredOrBusted(persistedQuery)) { |
|
|
await storage.removeItem(storageKey) |
|
|
} else { |
|
|
if (afterRestoreMacroTask) { |
|
|
|
|
|
setTimeout(() => afterRestoreMacroTask(persistedQuery), 0) |
|
|
} |
|
|
|
|
|
return persistedQuery.state.data as T |
|
|
} |
|
|
} |
|
|
} catch (err) { |
|
|
if (process.env.NODE_ENV === 'development') { |
|
|
console.error(err) |
|
|
console.warn( |
|
|
'Encountered an error attempting to restore query cache from persisted location.', |
|
|
) |
|
|
} |
|
|
await storage.removeItem(storageKey) |
|
|
} |
|
|
} |
|
|
|
|
|
return |
|
|
} |
|
|
|
|
|
async function persistQueryByKey( |
|
|
queryKey: QueryKey, |
|
|
queryClient: QueryClient, |
|
|
) { |
|
|
if (storage != null) { |
|
|
const query = queryClient.getQueryCache().find({ queryKey }) |
|
|
if (query) { |
|
|
await persistQuery(query) |
|
|
} else { |
|
|
if (process.env.NODE_ENV === 'development') { |
|
|
console.warn( |
|
|
'Could not find query to be persisted. QueryKey:', |
|
|
JSON.stringify(queryKey), |
|
|
) |
|
|
} |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
async function persistQuery(query: Query) { |
|
|
if (storage != null) { |
|
|
const storageKey = `${prefix}-${query.queryHash}` |
|
|
storage.setItem( |
|
|
storageKey, |
|
|
await serialize({ |
|
|
state: query.state, |
|
|
queryKey: query.queryKey, |
|
|
queryHash: query.queryHash, |
|
|
buster: buster, |
|
|
}), |
|
|
) |
|
|
} |
|
|
} |
|
|
|
|
|
async function persisterFn<T, TQueryKey extends QueryKey>( |
|
|
queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>, |
|
|
ctx: QueryFunctionContext<TQueryKey>, |
|
|
query: Query, |
|
|
) { |
|
|
const matchesFilter = filters ? matchQuery(filters, query) : true |
|
|
|
|
|
|
|
|
if (matchesFilter && query.state.data === undefined && storage != null) { |
|
|
const restoredData = await retrieveQuery( |
|
|
query.queryHash, |
|
|
(persistedQuery: PersistedQuery) => { |
|
|
|
|
|
query.setState({ |
|
|
dataUpdatedAt: persistedQuery.state.dataUpdatedAt, |
|
|
errorUpdatedAt: persistedQuery.state.errorUpdatedAt, |
|
|
}) |
|
|
|
|
|
if (query.isStale()) { |
|
|
query.fetch() |
|
|
} |
|
|
}, |
|
|
) |
|
|
|
|
|
if (restoredData != null) { |
|
|
return Promise.resolve(restoredData as T) |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
const queryFnResult = await queryFn(ctx) |
|
|
|
|
|
if (matchesFilter && storage != null) { |
|
|
|
|
|
setTimeout(() => { |
|
|
persistQuery(query) |
|
|
}, 0) |
|
|
} |
|
|
|
|
|
return Promise.resolve(queryFnResult) |
|
|
} |
|
|
|
|
|
async function persisterGc() { |
|
|
if (storage?.entries) { |
|
|
const entries = await storage.entries() |
|
|
for (const [key, value] of entries) { |
|
|
if (key.startsWith(prefix)) { |
|
|
const persistedQuery = await deserialize(value) |
|
|
|
|
|
if (isExpiredOrBusted(persistedQuery)) { |
|
|
await storage.removeItem(key) |
|
|
} |
|
|
} |
|
|
} |
|
|
} else if (process.env.NODE_ENV === 'development') { |
|
|
throw new Error( |
|
|
'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.', |
|
|
) |
|
|
} |
|
|
} |
|
|
|
|
|
async function restoreQueries( |
|
|
queryClient: QueryClient, |
|
|
filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {}, |
|
|
): Promise<void> { |
|
|
const { exact, queryKey } = filters |
|
|
|
|
|
if (storage?.entries) { |
|
|
const entries = await storage.entries() |
|
|
for (const [key, value] of entries) { |
|
|
if (key.startsWith(prefix)) { |
|
|
const persistedQuery = await deserialize(value) |
|
|
|
|
|
if (isExpiredOrBusted(persistedQuery)) { |
|
|
await storage.removeItem(key) |
|
|
continue |
|
|
} |
|
|
|
|
|
if (queryKey) { |
|
|
if (exact) { |
|
|
if (persistedQuery.queryHash !== hashKey(queryKey)) { |
|
|
continue |
|
|
} |
|
|
} else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) { |
|
|
continue |
|
|
} |
|
|
} |
|
|
|
|
|
queryClient.setQueryData( |
|
|
persistedQuery.queryKey, |
|
|
persistedQuery.state.data, |
|
|
{ |
|
|
updatedAt: persistedQuery.state.dataUpdatedAt, |
|
|
}, |
|
|
) |
|
|
} |
|
|
} |
|
|
} else if (process.env.NODE_ENV === 'development') { |
|
|
throw new Error( |
|
|
'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.', |
|
|
) |
|
|
} |
|
|
} |
|
|
|
|
|
return { |
|
|
persisterFn, |
|
|
persistQuery, |
|
|
persistQueryByKey, |
|
|
retrieveQuery, |
|
|
persisterGc, |
|
|
restoreQueries, |
|
|
} |
|
|
} |
|
|
|