Open History to see the last commit
1import { QueryClient } from '../core'
2import { getLogger } from '../core/logger'
3import {
4 dehydrate,
5 DehydratedState,
6 DehydrateOptions,
7 HydrateOptions,
8 hydrate,
9} from 'react-query'
10import { Promisable } from 'type-fest'
11β
12export interface Persistor {
13 persistClient(persistClient: PersistedClient): Promisable<void>
14 restoreClient(): Promisable<PersistedClient | undefined>
15 removeClient(): Promisable<void>
16}
17β
18export interface PersistedClient {
19 timestamp: number
20 buster: string
21 clientState: DehydratedState
22}
23β
24export interface PersistQueryClientOptions {
25 /** The QueryClient to persist */
26 queryClient: QueryClient
27 /** The Persistor interface for storing and restoring the cache
28 * to/from a persisted location */
29 persistor: Persistor
30 /** The max-allowed age of the cache.
31 * If a persisted cache is found that is older than this
32 * time, it will be discarded */
33 maxAge?: number
34 /** A unique string that can be used to forcefully
35 * invalidate existing caches if they do not share the same buster string */
36 buster?: string
37 /** The options passed to the hydrate function */
38 hydrateOptions?: HydrateOptions
39 /** The options passed to the dehydrate function */
40 dehydrateOptions?: DehydrateOptions
41}
42β
43export async function persistQueryClient({
44 queryClient,
45 persistor,
46 maxAge = 1000 * 60 * 60 * 24,
47 buster = '',
48 hydrateOptions,
49 dehydrateOptions,
50}: PersistQueryClientOptions) {
51 if (typeof window !== 'undefined') {
52 // Subscribe to changes
53 const saveClient = () => {
54 const persistClient: PersistedClient = {
55 buster,
56 timestamp: Date.now(),
57 clientState: dehydrate(queryClient, dehydrateOptions),
58 }
59β
60 persistor.persistClient(persistClient)
61 }
62β
63 // Attempt restore
64 try {
65 const persistedClient = await persistor.restoreClient()
66β
67 if (persistedClient) {
68 if (persistedClient.timestamp) {
69 const expired = Date.now() - persistedClient.timestamp > maxAge
70 const busted = persistedClient.buster !== buster
71 if (expired || busted) {
72 persistor.removeClient()
73 } else {
74 hydrate(queryClient, persistedClient.clientState, hydrateOptions)
75 }
76 } else {
77 persistor.removeClient()
78 }
79 }
80 } catch (err) {
81 getLogger().error(err)
82 getLogger().warn(
83 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.'
84 )
85 persistor.removeClient()
86 }
87β
88 // Subscribe to changes in the query cache to trigger the save
89 queryClient.getQueryCache().subscribe(saveClient)
90 }
91}