Open History to see the last commit
1import {
2 QueryClient,
3 dehydrate,
4 DehydratedState,
5 DehydrateOptions,
6 HydrateOptions,
7 hydrate,
8} from '../core'
9import { Promisable } from 'type-fest'
10β
11export interface Persister {
12 persistClient(persistClient: PersistedClient): Promisable<void>
13 restoreClient(): Promisable<PersistedClient | undefined>
14 removeClient(): Promisable<void>
15}
16β
17export interface PersistedClient {
18 timestamp: number
19 buster: string
20 clientState: DehydratedState
21}
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
32}
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
42}
43β
44export interface PersistedQueryClientSaveOptions
45 extends PersistQueryClienRootOptions {
46 /** The options passed to the dehydrate function */
47 dehydrateOptions?: DehydrateOptions
48}
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 if (typeof window !== 'undefined') {
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 }
96 }
97}
98β
99/**
100 * Persists data from the QueryCache
101 * - data dehydrated using dehydrateOptions
102 * - data is persisted using persister.persistClient
103 */
104export async function persistQueryClientSave({
105 queryClient,
106 persister,
107 buster = '',
108 dehydrateOptions,
109}: PersistedQueryClientSaveOptions) {
110 if (typeof window !== 'undefined') {
111 const persistClient: PersistedClient = {
112 buster,
113 timestamp: Date.now(),
114 clientState: dehydrate(queryClient, dehydrateOptions),
115 }
116β
117 await persister.persistClient(persistClient)
118 }
119}
120β
121/**
122 * Subscribe to QueryCache and MutationCache updates (for persisting)
123 * @returns an unsubscribe function (to discontinue monitoring)
124 */
125export function persistQueryClientSubscribe(
126 props: PersistedQueryClientSaveOptions
127) {
128 const unsubscribeQueryCache = props.queryClient
129 .getQueryCache()
130 .subscribe(() => {
131 persistQueryClientSave(props)
132 })
133β
134 const unusbscribeMutationCache = props.queryClient
135 .getMutationCache()
136 .subscribe(() => {
137 persistQueryClientSave(props)
138 })
139β
140 return () => {
141 unsubscribeQueryCache()
142 unusbscribeMutationCache()
143 }
144}
145β
146/**
147 * Restores persisted data to QueryCache and persists further changes.
148 */
149export function persistQueryClient(
150 props: PersistQueryClientOptions
151): [() => void, Promise<void>] {
152 let hasUnsubscribed = false
153 let persistQueryClientUnsubscribe: (() => void) | undefined
154 const unsubscribe = () => {
155 hasUnsubscribed = true
156 persistQueryClientUnsubscribe?.()
157 }
158β
159 let restorePromise = Promise.resolve()
160β
161 if (typeof window !== 'undefined') {
162 // Attempt restore
163 restorePromise = persistQueryClientRestore(props).then(() => {
164 if (!hasUnsubscribed) {
165 // Subscribe to changes in the query cache to trigger the save
166 persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)
167 }
168 })
169 }
170β
171 return [unsubscribe, restorePromise]
172}