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

persist.ts

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