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

persist.ts

179 lines5.0 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​
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 PersistQueryClientRootOptions {
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 extends PersistQueryClientRootOptions {
36 /** The max-allowed age of the cache in milliseconds.
37 * If a persisted cache is found that is older than this
38 * time, it will be discarded */
39 maxAge?: number
40 /** The options passed to the hydrate function */
41 hydrateOptions?: HydrateOptions
43​
44export interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {
45 /** The options passed to the dehydrate function */
46 dehydrateOptions?: DehydrateOptions
48​
49export interface PersistQueryClientOptions
50 extends
51 PersistedQueryClientRestoreOptions,
52 PersistedQueryClientSaveOptions,
53 PersistQueryClientRootOptions {}
54​
55/**
56 * Checks if emitted event is about cache change and not about observers.
57 * Useful for persist, where we only want to trigger save when cache is changed.
58 */
59const cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']
60​
61function isCacheEventType(eventType: NotifyEventType) {
62 return cacheEventTypes.includes(eventType)
64​
65/**
66 * Restores persisted data to the QueryCache
67 * - data obtained from persister.restoreClient
68 * - data is hydrated using hydrateOptions
69 * If data is expired, busted, empty, or throws, it runs persister.removeClient
70 */
71export async function persistQueryClientRestore({
72 queryClient,
73 persister,
74 maxAge = 1000 * 60 * 60 * 24,
75 buster = '',
76 hydrateOptions,
77}: PersistedQueryClientRestoreOptions) {
78 try {
79 const persistedClient = await persister.restoreClient()
80​
81 if (persistedClient) {
82 if (persistedClient.timestamp) {
83 const expired = Date.now() - persistedClient.timestamp > maxAge
84 const busted = persistedClient.buster !== buster
85 if (expired || busted) {
86 return persister.removeClient()
87 } else {
88 hydrate(queryClient, persistedClient.clientState, hydrateOptions)
89 }
90 } else {
91 return persister.removeClient()
92 }
93 }
94 } catch (err) {
95 if (process.env.NODE_ENV !== 'production') {
96 console.error(err)
97 console.warn(
98 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',
99 )
100 }
101​
102 await persister.removeClient()
103​
104 throw err
105 }
107​
108/**
109 * Persists data from the QueryCache
110 * - data dehydrated using dehydrateOptions
111 * - data is persisted using persister.persistClient
112 */
113export async function persistQueryClientSave({
114 queryClient,
115 persister,
116 buster = '',
117 dehydrateOptions,
118}: PersistedQueryClientSaveOptions) {
119 const persistClient: PersistedClient = {
120 buster,
121 timestamp: Date.now(),
122 clientState: dehydrate(queryClient, dehydrateOptions),
123 }
124​
125 await persister.persistClient(persistClient)
127​
128/**
129 * Subscribe to QueryCache and MutationCache updates (for persisting)
130 * @returns an unsubscribe function (to discontinue monitoring)
131 */
132export function persistQueryClientSubscribe(
133 props: PersistedQueryClientSaveOptions,
134) {
135 const unsubscribeQueryCache = props.queryClient
136 .getQueryCache()
137 .subscribe((event) => {
138 if (isCacheEventType(event.type)) {
139 persistQueryClientSave(props)
140 }
141 })
142​
143 const unsubscribeMutationCache = props.queryClient
144 .getMutationCache()
145 .subscribe((event) => {
146 if (isCacheEventType(event.type)) {
147 persistQueryClientSave(props)
148 }
149 })
150​
151 return () => {
152 unsubscribeQueryCache()
153 unsubscribeMutationCache()
154 }
156​
157/**
158 * Restores persisted data to QueryCache and persists further changes.
159 */
160export function persistQueryClient(
161 props: PersistQueryClientOptions,
162): [() => void, Promise<void>] {
163 let hasUnsubscribed = false
164 let persistQueryClientUnsubscribe: (() => void) | undefined
165 const unsubscribe = () => {
166 hasUnsubscribed = true
167 persistQueryClientUnsubscribe?.()
168 }
169​
170 // Attempt restore
171 const restorePromise = persistQueryClientRestore(props).then(() => {
172 if (!hasUnsubscribed) {
173 // Subscribe to changes in the query cache to trigger the save
174 persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)
175 }
176 })
177​
178 return [unsubscribe, restorePromise]