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

persist.ts

165 lines4.5 KB

1import {
2 QueryClient,
3 dehydrate,
4 DehydratedState,
5 DehydrateOptions,
6 HydrateOptions,
7 hydrate,
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 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 * Restores persisted data to the QueryCache
58 * - data obtained from persister.restoreClient
59 * - data is hydrated using hydrateOptions
60 * If data is expired, busted, empty, or throws, it runs persister.removeClient
61 */
62export async function persistQueryClientRestore({
63 queryClient,
64 persister,
65 maxAge = 1000 * 60 * 60 * 24,
66 buster = '',
67 hydrateOptions,
68}: PersistedQueryClientRestoreOptions) {
69 try {
70 const persistedClient = await persister.restoreClient()
71​
72 if (persistedClient) {
73 if (persistedClient.timestamp) {
74 const expired = Date.now() - persistedClient.timestamp > maxAge
75 const busted = persistedClient.buster !== buster
76 if (expired || busted) {
77 persister.removeClient()
78 } else {
79 hydrate(queryClient, persistedClient.clientState, hydrateOptions)
80 }
81 } else {
82 persister.removeClient()
83 }
84 }
85 } catch (err) {
86 if (process.env.NODE_ENV !== 'production') {
87 queryClient.getLogger().error(err)
88 queryClient
89 .getLogger()
90 .warn(
91 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',
92 )
93 }
94 persister.removeClient()
95 }
97​
98/**
99 * Persists data from the QueryCache
100 * - data dehydrated using dehydrateOptions
101 * - data is persisted using persister.persistClient
102 */
103export async function persistQueryClientSave({
104 queryClient,
105 persister,
106 buster = '',
107 dehydrateOptions,
108}: PersistedQueryClientSaveOptions) {
109 const persistClient: PersistedClient = {
110 buster,
111 timestamp: Date.now(),
112 clientState: dehydrate(queryClient, dehydrateOptions),
113 }
114​
115 await persister.persistClient(persistClient)
117​
118/**
119 * Subscribe to QueryCache and MutationCache updates (for persisting)
120 * @returns an unsubscribe function (to discontinue monitoring)
121 */
122export function persistQueryClientSubscribe(
123 props: PersistedQueryClientSaveOptions,
124) {
125 const unsubscribeQueryCache = props.queryClient
126 .getQueryCache()
127 .subscribe(() => {
128 persistQueryClientSave(props)
129 })
130​
131 const unusbscribeMutationCache = props.queryClient
132 .getMutationCache()
133 .subscribe(() => {
134 persistQueryClientSave(props)
135 })
136​
137 return () => {
138 unsubscribeQueryCache()
139 unusbscribeMutationCache()
140 }
142​
143/**
144 * Restores persisted data to QueryCache and persists further changes.
145 */
146export function persistQueryClient(
147 props: PersistQueryClientOptions,
148): [() => void, Promise<void>] {
149 let hasUnsubscribed = false
150 let persistQueryClientUnsubscribe: (() => void) | undefined
151 const unsubscribe = () => {
152 hasUnsubscribed = true
153 persistQueryClientUnsubscribe?.()
154 }
155​
156 // Attempt restore
157 const restorePromise = persistQueryClientRestore(props).then(() => {
158 if (!hasUnsubscribed) {
159 // Subscribe to changes in the query cache to trigger the save
160 persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)
161 }
162 })
163​
164 return [unsubscribe, restorePromise]