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

persist.ts

238 lines7.1 KB

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​
10/** A value, or a promise-like that resolves to it. */
11export type Promisable<T> = T | PromiseLike<T>
12​
13/** Saves, restores, and removes a {@link PersistedClient} in a storage. */
14export interface Persister {
15 /** Saves the persisted client to the storage. */
16 persistClient: (persistClient: PersistedClient) => Promisable<void>
17 /**
18 * Reads the persisted client from the storage, or `undefined` if nothing was
19 * saved.
20 */
21 restoreClient: () => Promisable<PersistedClient | undefined>
22 /** Removes the persisted client from the storage. */
23 removeClient: () => Promisable<void>
25​
26/**
27 * The dehydrated state of a `QueryClient` as it is persisted, with the time it
28 * was saved and its `buster`.
29 */
30export interface PersistedClient {
31 /**
32 * When the client was saved, in milliseconds since the epoch. Compared with
33 * `maxAge` on restore.
34 */
35 timestamp: number
36 /**
37 * The `buster` the client was saved with. A persisted client with a different
38 * `buster` is discarded.
39 */
40 buster: string
41 /** The dehydrated cache of the `QueryClient`. */
42 clientState: DehydratedState
44​
45/** The options shared by restoring and saving a persisted `QueryClient`. */
46export interface PersistQueryClientRootOptions {
47 /** The QueryClient to persist */
48 queryClient: QueryClient
49 /**
50 * The Persister interface for storing and restoring the cache to/from a
51 * persisted location
52 */
53 persister: Persister
54 /**
55 * A unique string that can be used to forcefully invalidate existing caches
56 * if they do not share the same buster string
57 */
58 buster?: string
60​
61/**
62 * Options for restoring a persisted `QueryClient` with
63 * {@link persistQueryClientRestore}.
64 */
65export interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {
66 /**
67 * The max-allowed age of the cache in milliseconds. If a persisted cache is
68 * found that is older than this time, it will be discarded
69 */
70 maxAge?: number
71 /** The options passed to the hydrate function */
72 hydrateOptions?: HydrateOptions
74​
75/** Options for saving a `QueryClient` with {@link persistQueryClientSave}. */
76export interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {
77 /** The options passed to the dehydrate function */
78 dehydrateOptions?: DehydrateOptions
80​
81/**
82 * Options for {@link persistQueryClient}, which both restores and saves a
83 * `QueryClient`.
84 */
85export interface PersistQueryClientOptions
86 extends
87 PersistedQueryClientRestoreOptions,
88 PersistedQueryClientSaveOptions,
89 PersistQueryClientRootOptions {}
90​
91const cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']
92​
93/**
94 * Checks if emitted event is about cache change and not about observers. Useful
95 * for persist, where we only want to trigger save when cache is changed.
96 *
97 * @param eventType - The type of the emitted event.
98 * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.
99 */
100function isCacheEventType(eventType: NotifyEventType) {
101 return cacheEventTypes.includes(eventType)
103​
104/**
105 * Restores persisted data to the QueryCache.
106 *
107 * - Data obtained from persister.restoreClient.
108 * - Data is hydrated using hydrateOptions. If data is expired, busted, empty, or
109 * throws, it runs persister.removeClient.
110 *
111 * @param options - The `queryClient` to restore into, the `persister`, and the
112 * `maxAge`, `buster`, and `hydrateOptions` that decide whether and how the
113 * persisted data is restored.
114 * @returns A promise that resolves once the data is restored or removed. If
115 * restoring throws, it attempts to remove the persisted data and then rejects
116 * with the restore error, or with the removal error if the removal fails
117 * too.
118 */
119export async function persistQueryClientRestore({
120 queryClient,
121 persister,
122 maxAge = 1000 * 60 * 60 * 24,
123 buster = '',
124 hydrateOptions,
125}: PersistedQueryClientRestoreOptions) {
126 try {
127 const persistedClient = await persister.restoreClient()
128​
129 if (persistedClient) {
130 if (persistedClient.timestamp) {
131 const expired = Date.now() - persistedClient.timestamp > maxAge
132 const busted = persistedClient.buster !== buster
133 if (expired || busted) {
134 return persister.removeClient()
135 } else {
136 hydrate(queryClient, persistedClient.clientState, hydrateOptions)
137 }
138 } else {
139 return persister.removeClient()
140 }
141 }
142 } catch (err) {
143 if (process.env.NODE_ENV !== 'production') {
144 console.error(err)
145 console.warn(
146 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',
147 )
148 }
149​
150 await persister.removeClient()
151​
152 throw err
153 }
155​
156/**
157 * Persists data from the QueryCache.
158 *
159 * - Data dehydrated using dehydrateOptions.
160 * - Data is persisted using persister.persistClient.
161 *
162 * @param options - The `queryClient` to persist, the `persister`, the `buster`,
163 * and the `dehydrateOptions`.
164 */
165export async function persistQueryClientSave({
166 queryClient,
167 persister,
168 buster = '',
169 dehydrateOptions,
170}: PersistedQueryClientSaveOptions) {
171 const persistClient: PersistedClient = {
172 buster,
173 timestamp: Date.now(),
174 clientState: dehydrate(queryClient, dehydrateOptions),
175 }
176​
177 await persister.persistClient(persistClient)
179​
180/**
181 * Subscribe to QueryCache and MutationCache updates (for persisting).
182 *
183 * @param props - The `queryClient` to monitor, the `persister`, the `buster`,
184 * and the `dehydrateOptions` used for each save.
185 * @returns An unsubscribe function (to discontinue monitoring)
186 */
187export function persistQueryClientSubscribe(
188 props: PersistedQueryClientSaveOptions,
189) {
190 const unsubscribeQueryCache = props.queryClient
191 .getQueryCache()
192 .subscribe((event) => {
193 if (isCacheEventType(event.type)) {
194 persistQueryClientSave(props)
195 }
196 })
197​
198 const unsubscribeMutationCache = props.queryClient
199 .getMutationCache()
200 .subscribe((event) => {
201 if (isCacheEventType(event.type)) {
202 persistQueryClientSave(props)
203 }
204 })
205​
206 return () => {
207 unsubscribeQueryCache()
208 unsubscribeMutationCache()
209 }
211​
212/**
213 * Restores persisted data to QueryCache and persists further changes.
214 *
215 * @param props - The options for both restoring and saving.
216 * @returns A tuple of a function that stops persisting, and a promise that
217 * resolves once the restore is done.
218 */
219export function persistQueryClient(
220 props: PersistQueryClientOptions,
221): [() => void, Promise<void>] {
222 let hasUnsubscribed = false
223 let persistQueryClientUnsubscribe: (() => void) | undefined
224 const unsubscribe = () => {
225 hasUnsubscribed = true
226 persistQueryClientUnsubscribe?.()
227 }
228​
229 // Attempt restore
230 const restorePromise = persistQueryClientRestore(props).then(() => {
231 if (!hasUnsubscribed) {
232 // Subscribe to changes in the query cache to trigger the save
233 persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)
234 }
235 })
236​
237 return [unsubscribe, restorePromise]