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

index.ts

79 lines2.3 KB

1import { QueryClient } from '../core'
2import { getLogger } from '../core/logger'
3import { dehydrate, DehydratedState, hydrate } from '../hydration'
4import { Promisable } from 'type-fest'
5​
6export interface Persistor {
7 persistClient(persistClient: PersistedClient): Promisable<void>
8 restoreClient(): Promisable<PersistedClient | undefined>
9 removeClient(): Promisable<void>
11​
12export interface PersistedClient {
13 timestamp: number
14 buster: string
15 clientState: DehydratedState
17​
18export interface PersistQueryClientOptions {
19 /** The QueryClient to persist */
20 queryClient: QueryClient
21 /** The Persistor interface for storing and restoring the cache
22 * to/from a persisted location */
23 persistor: Persistor
24 /** The max-allowed age of the cache.
25 * If a persisted cache is found that is older than this
26 * time, it will be discarded */
27 maxAge?: number
28 /** A unique string that can be used to forcefully
29 * invalidate existing caches if they do not share the same buster string */
30 buster?: string
32​
33export async function persistQueryClient({
34 queryClient,
35 persistor,
36 maxAge = 1000 * 60 * 60 * 24,
37 buster = '',
38}: PersistQueryClientOptions) {
39 if (typeof window !== 'undefined') {
40 // Subscribe to changes
41 const saveClient = () => {
42 const persistClient: PersistedClient = {
43 buster,
44 timestamp: Date.now(),
45 clientState: dehydrate(queryClient),
46 }
47​
48 persistor.persistClient(persistClient)
49 }
50​
51 // Attempt restore
52 try {
53 const persistedClient = await persistor.restoreClient()
54​
55 if (persistedClient) {
56 if (persistedClient.timestamp) {
57 const expired = Date.now() - persistedClient.timestamp > maxAge
58 const busted = persistedClient.buster !== buster
59 if (expired || busted) {
60 persistor.removeClient()
61 } else {
62 hydrate(queryClient, persistedClient.clientState)
63 }
64 } else {
65 persistor.removeClient()
66 }
67 }
68 } catch (err) {
69 getLogger().error(err)
70 getLogger().warn(
71 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.'
72 )
73 persistor.removeClient()
74 }
75​
76 // Subscribe to changes in the query cache to trigger the save
77 queryClient.getQueryCache().subscribe(saveClient)
78 }