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

persist.ts

164 lines4.5 KB

1import type {
2 QueryClient,
3 DehydratedState,
4 DehydrateOptions,
5 HydrateOptions,
6} from '@tanstack/query-core'
7import { dehydrate, hydrate } from '@tanstack/query-core'
8​
9export type Promisable<T> = T | PromiseLike<T>
10​
11export interface Persister {
12 persistClient(persistClient: PersistedClient): Promisable<void>
13 restoreClient(): Promisable<PersistedClient | undefined>
14 removeClient(): Promisable<void>
16​
17export interface PersistedClient {
18 timestamp: number
19 buster: string
20 clientState: DehydratedState
22​
23export interface PersistQueryClienRootOptions {
24 /** The QueryClient to persist */
25 queryClient: QueryClient
26 /** The Persister interface for storing and restoring the cache
27 * to/from a persisted location */
28 persister: Persister
29 /** A unique string that can be used to forcefully
30 * invalidate existing caches if they do not share the same buster string */
31 buster?: string
33​
34export interface PersistedQueryClientRestoreOptions
35 extends PersistQueryClienRootOptions {
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
45 extends PersistQueryClienRootOptions {
46 /** The options passed to the dehydrate function */
47 dehydrateOptions?: DehydrateOptions
49​
50export interface PersistQueryClientOptions
51 extends PersistedQueryClientRestoreOptions,
52 PersistedQueryClientSaveOptions,
53 PersistQueryClienRootOptions {}
54​
55/**
56 * Restores persisted data to the QueryCache
57 * - data obtained from persister.restoreClient
58 * - data is hydrated using hydrateOptions
59 * If data is expired, busted, empty, or throws, it runs persister.removeClient
60 */
61export async function persistQueryClientRestore({
62 queryClient,
63 persister,
64 maxAge = 1000 * 60 * 60 * 24,
65 buster = '',
66 hydrateOptions,
67}: PersistedQueryClientRestoreOptions) {
68 try {
69 const persistedClient = await persister.restoreClient()
70​
71 if (persistedClient) {
72 if (persistedClient.timestamp) {
73 const expired = Date.now() - persistedClient.timestamp > maxAge
74 const busted = persistedClient.buster !== buster
75 if (expired || busted) {
76 persister.removeClient()
77 } else {
78 hydrate(queryClient, persistedClient.clientState, hydrateOptions)
79 }
80 } else {
81 persister.removeClient()
82 }
83 }
84 } catch (err) {
85 if (process.env.NODE_ENV !== 'production') {
86 queryClient.getLogger().error(err)
87 queryClient
88 .getLogger()
89 .warn(
90 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',
91 )
92 }
93 persister.removeClient()
94 }
96​
97/**
98 * Persists data from the QueryCache
99 * - data dehydrated using dehydrateOptions
100 * - data is persisted using persister.persistClient
101 */
102export async function persistQueryClientSave({
103 queryClient,
104 persister,
105 buster = '',
106 dehydrateOptions,
107}: PersistedQueryClientSaveOptions) {
108 const persistClient: PersistedClient = {
109 buster,
110 timestamp: Date.now(),
111 clientState: dehydrate(queryClient, dehydrateOptions),
112 }
113​
114 await persister.persistClient(persistClient)
116​
117/**
118 * Subscribe to QueryCache and MutationCache updates (for persisting)
119 * @returns an unsubscribe function (to discontinue monitoring)
120 */
121export function persistQueryClientSubscribe(
122 props: PersistedQueryClientSaveOptions,
123) {
124 const unsubscribeQueryCache = props.queryClient
125 .getQueryCache()
126 .subscribe(() => {
127 persistQueryClientSave(props)
128 })
129​
130 const unusbscribeMutationCache = props.queryClient
131 .getMutationCache()
132 .subscribe(() => {
133 persistQueryClientSave(props)
134 })
135​
136 return () => {
137 unsubscribeQueryCache()
138 unusbscribeMutationCache()
139 }
141​
142/**
143 * Restores persisted data to QueryCache and persists further changes.
144 */
145export function persistQueryClient(
146 props: PersistQueryClientOptions,
147): [() => void, Promise<void>] {
148 let hasUnsubscribed = false
149 let persistQueryClientUnsubscribe: (() => void) | undefined
150 const unsubscribe = () => {
151 hasUnsubscribed = true
152 persistQueryClientUnsubscribe?.()
153 }
154​
155 // Attempt restore
156 const restorePromise = persistQueryClientRestore(props).then(() => {
157 if (!hasUnsubscribed) {
158 // Subscribe to changes in the query cache to trigger the save
159 persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)
160 }
161 })
162​
163 return [unsubscribe, restorePromise]