Open History to see the last commit
1import { dehydrate, hydrate } from '@tanstack/query-core'
2import type {
3 DehydrateOptions,
4 DehydratedState,
5 HydrateOptions,
6 NotifyEventType,
7 QueryClient,
8} from '@tanstack/query-core'
9β
10export type Promisable<T> = T | PromiseLike<T>
11β
12export interface Persister {
13 persistClient(persistClient: PersistedClient): Promisable<void>
14 restoreClient(): Promisable<PersistedClient | undefined>
15 removeClient(): Promisable<void>
16}
17β
18export interface PersistedClient {
19 timestamp: number
20 buster: string
21 clientState: DehydratedState
22}
23β
24export interface PersistQueryClienRootOptions {
25 /** The QueryClient to persist */
26 queryClient: QueryClient
27 /** The Persister interface for storing and restoring the cache
28 * to/from a persisted location */
29 persister: Persister
30 /** A unique string that can be used to forcefully
31 * invalidate existing caches if they do not share the same buster string */
32 buster?: string
33}
34β
35export interface PersistedQueryClientRestoreOptions
36 extends PersistQueryClienRootOptions {
37 /** The max-allowed age of the cache in milliseconds.
38 * If a persisted cache is found that is older than this
39 * time, it will be discarded */
40 maxAge?: number
41 /** The options passed to the hydrate function */
42 hydrateOptions?: HydrateOptions
43}
44β
45export interface PersistedQueryClientSaveOptions
46 extends PersistQueryClienRootOptions {
47 /** The options passed to the dehydrate function */
48 dehydrateOptions?: DehydrateOptions
49}
50β
51export interface PersistQueryClientOptions
52 extends PersistedQueryClientRestoreOptions,
53 PersistedQueryClientSaveOptions,
54 PersistQueryClienRootOptions {}
55β
56/**
57 * Checks if emitted event is about cache change and not about observers.
58 * Useful for persist, where we only want to trigger save when cache is changed.
59 */
60const cacheableEventTypes: Array<NotifyEventType> = [
61 'added',
62 'removed',
63 'updated',
64]
65β
66function isCacheableEventType(eventType: NotifyEventType) {
67 return cacheableEventTypes.includes(eventType)
68}
69β
70/**
71 * Restores persisted data to the QueryCache
72 * - data obtained from persister.restoreClient
73 * - data is hydrated using hydrateOptions
74 * If data is expired, busted, empty, or throws, it runs persister.removeClient
75 */
76export async function persistQueryClientRestore({
77 queryClient,
78 persister,
79 maxAge = 1000 * 60 * 60 * 24,
80 buster = '',
81 hydrateOptions,
82}: PersistedQueryClientRestoreOptions) {
83 try {
84 const persistedClient = await persister.restoreClient()
85β
86 if (persistedClient) {
87 if (persistedClient.timestamp) {
88 const expired = Date.now() - persistedClient.timestamp > maxAge
89 const busted = persistedClient.buster !== buster
90 if (expired || busted) {
91 persister.removeClient()
92 } else {
93 hydrate(queryClient, persistedClient.clientState, hydrateOptions)
94 }
95 } else {
96 persister.removeClient()
97 }
98 }
99 } catch (err) {
100 if (process.env.NODE_ENV !== 'production') {
101 console.error(err)
102 console.warn(
103 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',
104 )
105 }
106 persister.removeClient()
107 }
108}
109β
110/**
111 * Persists data from the QueryCache
112 * - data dehydrated using dehydrateOptions
113 * - data is persisted using persister.persistClient
114 */
115export async function persistQueryClientSave({
116 queryClient,
117 persister,
118 buster = '',
119 dehydrateOptions,
120}: PersistedQueryClientSaveOptions) {
121 const persistClient: PersistedClient = {
122 buster,
123 timestamp: Date.now(),
124 clientState: dehydrate(queryClient, dehydrateOptions),
125 }
126β
127 await persister.persistClient(persistClient)
128}
129β
130/**
131 * Subscribe to QueryCache and MutationCache updates (for persisting)
132 * @returns an unsubscribe function (to discontinue monitoring)
133 */
134export function persistQueryClientSubscribe(
135 props: PersistedQueryClientSaveOptions,
136) {
137 const unsubscribeQueryCache = props.queryClient
138 .getQueryCache()
139 .subscribe((event) => {
140 if (isCacheableEventType(event.type)) {
141 persistQueryClientSave(props)
142 }
143 })
144β
145 const unusbscribeMutationCache = props.queryClient
146 .getMutationCache()
147 .subscribe((event) => {
148 if (isCacheableEventType(event.type)) {
149 persistQueryClientSave(props)
150 }
151 })
152β
153 return () => {
154 unsubscribeQueryCache()
155 unusbscribeMutationCache()
156 }
157}
158β
159/**
160 * Restores persisted data to QueryCache and persists further changes.
161 */
162export function persistQueryClient(
163 props: PersistQueryClientOptions,
164): [() => void, Promise<void>] {
165 let hasUnsubscribed = false
166 let persistQueryClientUnsubscribe: (() => void) | undefined
167 const unsubscribe = () => {
168 hasUnsubscribed = true
169 persistQueryClientUnsubscribe?.()
170 }
171β
172 // Attempt restore
173 const restorePromise = persistQueryClientRestore(props).then(() => {
174 if (!hasUnsubscribed) {
175 // Subscribe to changes in the query cache to trigger the save
176 persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)
177 }
178 })
179β
180 return [unsubscribe, restorePromise]
181}