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

persist.ts

183 lines5.1 KB

1import { dehydrate, hydrate } from '@tanstack/query-core'
2import type {
3 DehydrateOptions,
4 DehydratedState,
5 HydrateOptions,
6 QueryClient,
7} from '@tanstack/query-core'
8import type { NotifyEventType } 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>
17​
18export interface PersistedClient {
19 timestamp: number
20 buster: string
21 clientState: DehydratedState
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
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
44​
45export interface PersistedQueryClientSaveOptions
46 extends PersistQueryClienRootOptions {
47 /** The options passed to the dehydrate function */
48 dehydrateOptions?: DehydrateOptions
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',
65​
66function isCacheableEventType(eventType: NotifyEventType) {
67 return cacheableEventTypes.includes(eventType)
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 queryClient.getLogger().error(err)
102 queryClient
103 .getLogger()
104 .warn(
105 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',
106 )
107 }
108 persister.removeClient()
109 }
111​
112/**
113 * Persists data from the QueryCache
114 * - data dehydrated using dehydrateOptions
115 * - data is persisted using persister.persistClient
116 */
117export async function persistQueryClientSave({
118 queryClient,
119 persister,
120 buster = '',
121 dehydrateOptions,
122}: PersistedQueryClientSaveOptions) {
123 const persistClient: PersistedClient = {
124 buster,
125 timestamp: Date.now(),
126 clientState: dehydrate(queryClient, dehydrateOptions),
127 }
128​
129 await persister.persistClient(persistClient)
131​
132/**
133 * Subscribe to QueryCache and MutationCache updates (for persisting)
134 * @returns an unsubscribe function (to discontinue monitoring)
135 */
136export function persistQueryClientSubscribe(
137 props: PersistedQueryClientSaveOptions,
138) {
139 const unsubscribeQueryCache = props.queryClient
140 .getQueryCache()
141 .subscribe((event) => {
142 if (isCacheableEventType(event.type)) {
143 persistQueryClientSave(props)
144 }
145 })
146​
147 const unusbscribeMutationCache = props.queryClient
148 .getMutationCache()
149 .subscribe((event) => {
150 if (isCacheableEventType(event.type)) {
151 persistQueryClientSave(props)
152 }
153 })
154​
155 return () => {
156 unsubscribeQueryCache()
157 unusbscribeMutationCache()
158 }
160​
161/**
162 * Restores persisted data to QueryCache and persists further changes.
163 */
164export function persistQueryClient(
165 props: PersistQueryClientOptions,
166): [() => void, Promise<void>] {
167 let hasUnsubscribed = false
168 let persistQueryClientUnsubscribe: (() => void) | undefined
169 const unsubscribe = () => {
170 hasUnsubscribed = true
171 persistQueryClientUnsubscribe?.()
172 }
173​
174 // Attempt restore
175 const restorePromise = persistQueryClientRestore(props).then(() => {
176 if (!hasUnsubscribed) {
177 // Subscribe to changes in the query cache to trigger the save
178 persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)
179 }
180 })
181​
182 return [unsubscribe, restorePromise]