buster/web/src/context/BusterReactQuery/createPersister.ts

56 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-03-29 02:53:20 +08:00
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
import { isServer } from '@tanstack/react-query';
import { PersistQueryClientProviderProps } from '@tanstack/react-query-persist-client';
import { queryKeys } from '@/api/query_keys';
import { hashKey } from '@tanstack/react-query';
import packageJson from '../../../package.json';
const buster = packageJson.version;
2025-03-29 07:30:02 +08:00
export const PERSIST_TIME = 1000 * 60 * 60 * 24 * 7; // 7 days
2025-03-29 02:53:20 +08:00
2025-04-23 23:44:56 +08:00
export const PERSISTED_QUERIES = [].map(hashKey);
2025-03-29 02:53:20 +08:00
export const PERMANENT_QUERIES = [queryKeys.getCurrencies.queryKey].map(hashKey);
const ALL_PERSISTED_QUERIES = [...PERSISTED_QUERIES, ...PERMANENT_QUERIES];
2025-03-29 07:30:02 +08:00
const persister = createSyncStoragePersister({
key: 'buster-query-cache',
storage: isServer ? undefined : window.localStorage,
throttleTime: 1500, // 1.5 seconds,
serialize: (client) => {
/*
* Make persisted queries appear stale on first load by setting the dataUpdatedAt to 1 (NOT 0)
* This way the query will be refetched from the server when it is first mounted AND we
* don't have to deal with the flash of stale data that would otherwise happen.
*/
client.clientState.queries.forEach((query) => {
const isPermanentQuery = PERMANENT_QUERIES.includes(query.queryHash);
if (!isPermanentQuery) {
query.state.dataUpdatedAt = 1;
}
});
return JSON.stringify(client);
}
});
2025-03-29 02:53:20 +08:00
export const persistOptions: PersistQueryClientProviderProps['persistOptions'] = {
persister: persister,
maxAge: PERSIST_TIME,
dehydrateOptions: {
shouldDehydrateQuery: (query) => {
2025-04-23 23:44:56 +08:00
const isList = query.queryKey[1] === 'list';
return isList || ALL_PERSISTED_QUERIES.includes(query.queryHash);
2025-03-29 02:53:20 +08:00
}
},
2025-03-29 07:30:02 +08:00
hydrateOptions: {
defaultOptions: {
queries: {
initialDataUpdatedAt: 0
}
}
},
2025-03-29 02:53:20 +08:00
buster: buster
};