@tanstack/query-persist-client-core 4.7.0 → 4.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -1,164 +1,2 @@
1
- import type {
2
- QueryClient,
3
- DehydratedState,
4
- DehydrateOptions,
5
- HydrateOptions,
6
- } from '@tanstack/query-core'
7
- import { dehydrate, hydrate } from '@tanstack/query-core'
8
-
9
- export type Promisable<T> = T | PromiseLike<T>
10
-
11
- export interface Persister {
12
- persistClient(persistClient: PersistedClient): Promisable<void>
13
- restoreClient(): Promisable<PersistedClient | undefined>
14
- removeClient(): Promisable<void>
15
- }
16
-
17
- export interface PersistedClient {
18
- timestamp: number
19
- buster: string
20
- clientState: DehydratedState
21
- }
22
-
23
- export 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
-
34
- export 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
-
44
- export interface PersistedQueryClientSaveOptions
45
- extends PersistQueryClienRootOptions {
46
- /** The options passed to the dehydrate function */
47
- dehydrateOptions?: DehydrateOptions
48
- }
49
-
50
- export 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
- */
61
- export 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
- }
95
- }
96
-
97
- /**
98
- * Persists data from the QueryCache
99
- * - data dehydrated using dehydrateOptions
100
- * - data is persisted using persister.persistClient
101
- */
102
- export 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)
115
- }
116
-
117
- /**
118
- * Subscribe to QueryCache and MutationCache updates (for persisting)
119
- * @returns an unsubscribe function (to discontinue monitoring)
120
- */
121
- export 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
- }
140
- }
141
-
142
- /**
143
- * Restores persisted data to QueryCache and persists further changes.
144
- */
145
- export 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]
164
- }
1
+ export * from './persist'
2
+ export * from './retryStrategies'
package/src/persist.ts ADDED
@@ -0,0 +1,164 @@
1
+ import type {
2
+ QueryClient,
3
+ DehydratedState,
4
+ DehydrateOptions,
5
+ HydrateOptions,
6
+ } from '@tanstack/query-core'
7
+ import { dehydrate, hydrate } from '@tanstack/query-core'
8
+
9
+ export type Promisable<T> = T | PromiseLike<T>
10
+
11
+ export interface Persister {
12
+ persistClient(persistClient: PersistedClient): Promisable<void>
13
+ restoreClient(): Promisable<PersistedClient | undefined>
14
+ removeClient(): Promisable<void>
15
+ }
16
+
17
+ export interface PersistedClient {
18
+ timestamp: number
19
+ buster: string
20
+ clientState: DehydratedState
21
+ }
22
+
23
+ export 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
+
34
+ export 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
+
44
+ export interface PersistedQueryClientSaveOptions
45
+ extends PersistQueryClienRootOptions {
46
+ /** The options passed to the dehydrate function */
47
+ dehydrateOptions?: DehydrateOptions
48
+ }
49
+
50
+ export 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
+ */
61
+ export 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
+ }
95
+ }
96
+
97
+ /**
98
+ * Persists data from the QueryCache
99
+ * - data dehydrated using dehydrateOptions
100
+ * - data is persisted using persister.persistClient
101
+ */
102
+ export 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)
115
+ }
116
+
117
+ /**
118
+ * Subscribe to QueryCache and MutationCache updates (for persisting)
119
+ * @returns an unsubscribe function (to discontinue monitoring)
120
+ */
121
+ export 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
+ }
140
+ }
141
+
142
+ /**
143
+ * Restores persisted data to QueryCache and persists further changes.
144
+ */
145
+ export 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]
164
+ }
@@ -0,0 +1,30 @@
1
+ import type { PersistedClient } from '@tanstack/query-persist-client-core'
2
+
3
+ export type PersistRetryer = (props: {
4
+ persistedClient: PersistedClient
5
+ error: Error
6
+ errorCount: number
7
+ }) => PersistedClient | undefined
8
+
9
+ export const removeOldestQuery: PersistRetryer = ({ persistedClient }) => {
10
+ const mutations = [...persistedClient.clientState.mutations]
11
+ const queries = [...persistedClient.clientState.queries]
12
+ const client: PersistedClient = {
13
+ ...persistedClient,
14
+ clientState: { mutations, queries },
15
+ }
16
+
17
+ // sort queries by dataUpdatedAt (oldest first)
18
+ const sortedQueries = [...queries].sort(
19
+ (a, b) => a.state.dataUpdatedAt - b.state.dataUpdatedAt,
20
+ )
21
+
22
+ // clean oldest query
23
+ if (sortedQueries.length > 0) {
24
+ const oldestData = sortedQueries.shift()
25
+ client.clientState.queries = queries.filter((q) => q !== oldestData)
26
+ return client
27
+ }
28
+
29
+ return undefined
30
+ }