@tanstack/query-persist-client-core 5.104.1 → 5.104.2
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/build/legacy/createPersister.cjs +64 -7
- package/build/legacy/createPersister.cjs.map +1 -1
- package/build/legacy/createPersister.d.cts +50 -9
- package/build/legacy/createPersister.d.cts.map +1 -1
- package/build/legacy/createPersister.d.ts +50 -9
- package/build/legacy/createPersister.d.ts.map +1 -1
- package/build/legacy/createPersister.js +64 -7
- package/build/legacy/createPersister.js.map +1 -1
- package/build/legacy/persist.cjs +26 -12
- package/build/legacy/persist.cjs.map +1 -1
- package/build/legacy/persist.d.cts +73 -14
- package/build/legacy/persist.d.cts.map +1 -1
- package/build/legacy/persist.d.ts +73 -14
- package/build/legacy/persist.d.ts.map +1 -1
- package/build/legacy/persist.js +26 -12
- package/build/legacy/persist.js.map +1 -1
- package/build/legacy/retryStrategies.cjs +6 -0
- package/build/legacy/retryStrategies.cjs.map +1 -1
- package/build/legacy/retryStrategies.d.cts +10 -0
- package/build/legacy/retryStrategies.d.cts.map +1 -1
- package/build/legacy/retryStrategies.d.ts +10 -0
- package/build/legacy/retryStrategies.d.ts.map +1 -1
- package/build/legacy/retryStrategies.js +6 -0
- package/build/legacy/retryStrategies.js.map +1 -1
- package/build/modern/createPersister.cjs +64 -7
- package/build/modern/createPersister.cjs.map +1 -1
- package/build/modern/createPersister.d.cts +50 -9
- package/build/modern/createPersister.d.cts.map +1 -1
- package/build/modern/createPersister.d.ts +50 -9
- package/build/modern/createPersister.d.ts.map +1 -1
- package/build/modern/createPersister.js +64 -7
- package/build/modern/createPersister.js.map +1 -1
- package/build/modern/persist.cjs +26 -12
- package/build/modern/persist.cjs.map +1 -1
- package/build/modern/persist.d.cts +73 -14
- package/build/modern/persist.d.cts.map +1 -1
- package/build/modern/persist.d.ts +73 -14
- package/build/modern/persist.d.ts.map +1 -1
- package/build/modern/persist.js +26 -12
- package/build/modern/persist.js.map +1 -1
- package/build/modern/retryStrategies.cjs +6 -0
- package/build/modern/retryStrategies.cjs.map +1 -1
- package/build/modern/retryStrategies.d.cts +10 -0
- package/build/modern/retryStrategies.d.cts.map +1 -1
- package/build/modern/retryStrategies.d.ts +10 -0
- package/build/modern/retryStrategies.d.ts.map +1 -1
- package/build/modern/retryStrategies.js +6 -0
- package/build/modern/retryStrategies.js.map +1 -1
- package/package.json +4 -4
- package/src/createPersister.ts +103 -9
- package/src/persist.ts +77 -16
- package/src/retryStrategies.ts +10 -0
|
@@ -9,15 +9,25 @@ const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
|
9
9
|
*
|
|
10
10
|
* ```
|
|
11
11
|
* useQuery({
|
|
12
|
-
queryKey: ['myKey'],
|
|
13
|
-
queryFn: fetcher,
|
|
14
|
-
persister: createPersister({
|
|
15
|
-
storage: localStorage,
|
|
16
|
-
}),
|
|
17
|
-
})
|
|
18
|
-
```
|
|
12
|
+
* queryKey: ['myKey'],
|
|
13
|
+
* queryFn: fetcher,
|
|
14
|
+
* persister: createPersister({
|
|
15
|
+
* storage: localStorage,
|
|
16
|
+
* }),
|
|
17
|
+
* })
|
|
18
|
+
* ```
|
|
19
|
+
* @param options - The storage to persist to, and the options for serializing, expiring, and
|
|
20
|
+
* filtering persisted queries.
|
|
21
|
+
* @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
|
|
22
|
+
* restore, remove, and garbage collect persisted queries manually.
|
|
19
23
|
*/
|
|
20
24
|
function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters }) {
|
|
25
|
+
/**
|
|
26
|
+
* Checks whether a persisted query should be discarded.
|
|
27
|
+
* @param persistedQuery - The persisted query to check.
|
|
28
|
+
* @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different
|
|
29
|
+
* `buster`.
|
|
30
|
+
*/
|
|
21
31
|
function isExpiredOrBusted(persistedQuery) {
|
|
22
32
|
if (persistedQuery.state.dataUpdatedAt) {
|
|
23
33
|
const expired = Date.now() - persistedQuery.state.dataUpdatedAt > maxAge;
|
|
@@ -27,6 +37,14 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
27
37
|
}
|
|
28
38
|
return true;
|
|
29
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are
|
|
42
|
+
* removed instead.
|
|
43
|
+
* @param queryHash - The hash of the query to read.
|
|
44
|
+
* @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.
|
|
45
|
+
* @returns A promise that resolves with the persisted data, or `undefined` if nothing was
|
|
46
|
+
* restored.
|
|
47
|
+
*/
|
|
30
48
|
async function retrieveQuery(queryHash, afterRestoreMacroTask) {
|
|
31
49
|
if (storage != null) {
|
|
32
50
|
const storageKey = `${prefix}-${queryHash}`;
|
|
@@ -55,6 +73,12 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
55
73
|
}
|
|
56
74
|
}
|
|
57
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Persists the query with the given key, if it exists in the client's cache.
|
|
78
|
+
* @param queryKey - The key of the query to persist.
|
|
79
|
+
* @param queryClient - The client whose cache holds the query.
|
|
80
|
+
* @returns A promise that resolves once the query is persisted.
|
|
81
|
+
*/
|
|
58
82
|
async function persistQueryByKey(queryKey, queryClient) {
|
|
59
83
|
if (storage != null) {
|
|
60
84
|
const query = queryClient.getQueryCache().find({ queryKey });
|
|
@@ -62,6 +86,11 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
62
86
|
else if (process.env.NODE_ENV === "development") console.warn("Could not find query to be persisted. QueryKey:", JSON.stringify(queryKey));
|
|
63
87
|
}
|
|
64
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* Writes a query's state, key, hash, and `buster` to storage.
|
|
91
|
+
* @param query - The query to persist.
|
|
92
|
+
* @returns A promise that resolves once the entry is serialized and written.
|
|
93
|
+
*/
|
|
65
94
|
async function persistQuery(query) {
|
|
66
95
|
if (storage != null) {
|
|
67
96
|
const storageKey = `${prefix}-${query.queryHash}`;
|
|
@@ -73,6 +102,14 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
73
102
|
}));
|
|
74
103
|
}
|
|
75
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* The `persister` of a query: restores its data from storage if the query has none yet, otherwise
|
|
107
|
+
* runs `queryFn` and persists the result.
|
|
108
|
+
* @param queryFn - The query's own query function.
|
|
109
|
+
* @param ctx - The context passed to `queryFn`.
|
|
110
|
+
* @param query - The query being fetched.
|
|
111
|
+
* @returns A promise that resolves with the restored or fetched data.
|
|
112
|
+
*/
|
|
76
113
|
async function persisterFn(queryFn, ctx, query) {
|
|
77
114
|
const matchesFilter = filters ? (0, _tanstack_query_core.matchQuery)(filters, query) : true;
|
|
78
115
|
if (matchesFilter && query.state.data === void 0 && storage != null) {
|
|
@@ -91,6 +128,11 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
91
128
|
});
|
|
92
129
|
return Promise.resolve(queryFnResult);
|
|
93
130
|
}
|
|
131
|
+
/**
|
|
132
|
+
* Removes expired, busted, or unreadable entries from storage. Requires the storage to implement
|
|
133
|
+
* `entries`.
|
|
134
|
+
* @returns A promise that resolves once every entry is checked.
|
|
135
|
+
*/
|
|
94
136
|
async function persisterGc() {
|
|
95
137
|
if (storage === null || storage === void 0 ? void 0 : storage.entries) {
|
|
96
138
|
const storageKeyPrefix = `${prefix}-`;
|
|
@@ -107,6 +149,14 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
107
149
|
}
|
|
108
150
|
} else if (process.env.NODE_ENV === "development") throw new Error("Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.");
|
|
109
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* Restores every persisted query matching `filters` into the client's cache with
|
|
154
|
+
* `queryClient.setQueryData`. Requires the storage to implement `entries`.
|
|
155
|
+
* @param queryClient - The client to restore the queries into.
|
|
156
|
+
* @param filters - The `queryKey` and `exact` filters to match. Without them, every query is
|
|
157
|
+
* restored.
|
|
158
|
+
* @returns A promise that resolves once every entry is checked.
|
|
159
|
+
*/
|
|
110
160
|
async function restoreQueries(queryClient, filters = {}) {
|
|
111
161
|
const { exact, queryKey } = filters;
|
|
112
162
|
if (storage === null || storage === void 0 ? void 0 : storage.entries) {
|
|
@@ -133,6 +183,13 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
133
183
|
}
|
|
134
184
|
} else if (process.env.NODE_ENV === "development") throw new Error("Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.");
|
|
135
185
|
}
|
|
186
|
+
/**
|
|
187
|
+
* Removes every persisted query matching `filters` from storage. Requires the storage to implement
|
|
188
|
+
* `entries`.
|
|
189
|
+
* @param filters - The `queryKey` and `exact` filters to match. Without them, every query is
|
|
190
|
+
* removed.
|
|
191
|
+
* @returns A promise that resolves once every entry is checked.
|
|
192
|
+
*/
|
|
136
193
|
async function removeQueries(filters = {}) {
|
|
137
194
|
const { exact, queryKey } = filters;
|
|
138
195
|
if (storage === null || storage === void 0 ? void 0 : storage.entries) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPersister.cjs","names":["matchQuery","hashKey","partialMatchKey"],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\nexport interface PersistedQuery {\n buster: string\n queryHash: string\n queryKey: QueryKey\n state: QueryState\n}\n\nexport type MaybePromise<T> = T | Promise<T>\n\nexport interface AsyncStorage<TStorageValue = string> {\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n removeItem: (key: string) => MaybePromise<void>\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /** The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n *\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n queryKey: ['myKey'],\n queryFn: fetcher,\n persister: createPersister({\n storage: localStorage,\n }),\n })\n ```\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;;AA8EA,MAAa,uBAAuB;;;;;;;;;;;;;;;;AAiBpC,SAAgB,kCAA0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,WAAW,GAAG;KAC5B;IACF;IAEA,IAAI,OACE;SAAA,eAAe,eAAA,GAAcD,qBAAAA,QAAAA,CAAQ,QAAQ,GAC/C;IAAA,OAEG,IAAI,EAAA,GAACC,qBAAAA,gBAAAA,CAAgB,eAAe,UAAU,QAAQ,GAC3D;IAGF,MAAM,QAAQ,WAAW,GAAG;GAC9B;EAEJ,OAAO,IAAI,QAAQ,IAAI,aAAa,eAClC,MAAM,IAAI,MACR,gJACF;CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"createPersister.cjs","names":["matchQuery","hashKey","partialMatchKey"],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\n * The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n * queryKey: ['myKey'],\n * queryFn: fetcher,\n * persister: createPersister({\n * storage: localStorage,\n * }),\n * })\n * ```\n * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\n */\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\n */\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\n */\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\n */\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\n */\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\n */\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,WACyC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAA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,QAAQ,GAC/C;IAAA,OAEG,IAAI,EAAA,GAACC,qBAAAA,gBAAAA,CAAgB,eAAe,UAAU,QAAQ,GAC3D;IAGF,MAAM,QAAQ,WAAW,GAAG;GAC9B;EAEJ,OAAO,IAAI,QAAQ,IAAI,aAAa,eAClC,MAAM,IAAI,MACR,gJACF;CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
@@ -1,20 +1,58 @@
|
|
|
1
1
|
import { Query, QueryClient, QueryFilters, QueryFunctionContext, QueryKey, QueryState } from "@tanstack/query-core";
|
|
2
2
|
//#region src/createPersister.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* A single query as stored by {@link experimental_createQueryPersister}.
|
|
5
|
+
*/
|
|
3
6
|
export interface PersistedQuery {
|
|
7
|
+
/**
|
|
8
|
+
* The `buster` the query was saved with. Entries with a different `buster` are discarded.
|
|
9
|
+
*/
|
|
4
10
|
buster: string;
|
|
11
|
+
/**
|
|
12
|
+
* The hash of the query.
|
|
13
|
+
*/
|
|
5
14
|
queryHash: string;
|
|
15
|
+
/**
|
|
16
|
+
* The key of the query.
|
|
17
|
+
*/
|
|
6
18
|
queryKey: QueryKey;
|
|
19
|
+
/**
|
|
20
|
+
* The state of the query, including its data and when it was last updated.
|
|
21
|
+
*/
|
|
7
22
|
state: QueryState;
|
|
8
23
|
}
|
|
24
|
+
/**
|
|
25
|
+
* A value, or a promise that resolves to it.
|
|
26
|
+
*/
|
|
9
27
|
export type MaybePromise<T> = T | Promise<T>;
|
|
28
|
+
/**
|
|
29
|
+
* A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous
|
|
30
|
+
* or return promises.
|
|
31
|
+
*/
|
|
10
32
|
export interface AsyncStorage<TStorageValue = string> {
|
|
33
|
+
/**
|
|
34
|
+
* Reads the value stored under `key`, or `null`/`undefined` if there is none.
|
|
35
|
+
*/
|
|
11
36
|
getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>;
|
|
37
|
+
/**
|
|
38
|
+
* Stores `value` under `key`.
|
|
39
|
+
*/
|
|
12
40
|
setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>;
|
|
41
|
+
/**
|
|
42
|
+
* Removes the value stored under `key`.
|
|
43
|
+
*/
|
|
13
44
|
removeItem: (key: string) => MaybePromise<void>;
|
|
45
|
+
/**
|
|
46
|
+
* Returns all stored key-value pairs. Required for removing expired entries in bulk.
|
|
47
|
+
*/
|
|
14
48
|
entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>;
|
|
15
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Options for {@link experimental_createQueryPersister}.
|
|
52
|
+
*/
|
|
16
53
|
export interface StoragePersisterOptions<TStorageValue = string> {
|
|
17
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* The storage client used for setting and retrieving items from cache.
|
|
18
56
|
* For SSR pass in `undefined`.
|
|
19
57
|
*/
|
|
20
58
|
storage: AsyncStorage<TStorageValue> | undefined | null;
|
|
@@ -50,7 +88,6 @@ export interface StoragePersisterOptions<TStorageValue = string> {
|
|
|
50
88
|
* If set to `true`, the query will refetch on successful query restoration if the data is stale.
|
|
51
89
|
* If set to `false`, the query will not refetch on successful query restoration.
|
|
52
90
|
* If set to `'always'`, the query will always refetch on successful query restoration.
|
|
53
|
-
*
|
|
54
91
|
* @defaultValue true
|
|
55
92
|
*/
|
|
56
93
|
refetchOnRestore?: boolean | 'always';
|
|
@@ -67,13 +104,17 @@ export declare const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
|
67
104
|
*
|
|
68
105
|
* ```
|
|
69
106
|
* useQuery({
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
107
|
+
* queryKey: ['myKey'],
|
|
108
|
+
* queryFn: fetcher,
|
|
109
|
+
* persister: createPersister({
|
|
110
|
+
* storage: localStorage,
|
|
111
|
+
* }),
|
|
112
|
+
* })
|
|
113
|
+
* ```
|
|
114
|
+
* @param options - The storage to persist to, and the options for serializing, expiring, and
|
|
115
|
+
* filtering persisted queries.
|
|
116
|
+
* @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
|
|
117
|
+
* restore, remove, and garbage collect persisted queries manually.
|
|
77
118
|
*/
|
|
78
119
|
export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters }: StoragePersisterOptions<TStorageValue>): {
|
|
79
120
|
persisterFn: <T, TQueryKey extends QueryKey>(queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>, ctx: QueryFunctionContext<TQueryKey>, query: Query) => Promise<T>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPersister.d.cts","names":[],"sources":["../../src/createPersister.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"createPersister.d.cts","names":[],"sources":["../../src/createPersister.ts"],"mappings":";;;;;iBAkBiB;;;;EAIf;;;;EAIA;;;;EAIA,UAAU;;;;EAIV,OAAO;;;;;YAMG,aAAa,KAAK,IAAI,QAAQ;;;;;iBAMzB,aAAa;;;;EAI5B,UAAU,gBAAgB,aAAa;;;;EAIvC,UAAU,aAAa,OAAO,kBAAkB;;;;EAIhD,aAAa,gBAAgB;;;;EAI7B,gBAAgB,aAAa,OAAO,aAAa,OAAO;;;;;iBAMzC,wBAAwB;;;;;EAKvC,SAAS,aAAa;;;;;EAKtB,aAAa,gBAAgB,mBAAmB,aAAa;;;;;EAK7D,eAAe,cAAc,kBAAkB,aAAa;;;;;EAK5D;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;EAIA,UAAU;;qBAGC;;;;;;;;;;;;;;;;;;;;wBAqBG,kCAAkC,0BAChD,SACA,QACA,QACA,WAGA,aAGA,QACA,kBACA,WACC,wBAAwB;EAgIE,cAAA,GAAG,kBAAkB,UAAQ,UAC5C,SAAS,qBAAqB,eAAe,IAAI,QAAQ,IAAE,KAChE,qBAAqB,YAAU,OAC7B,UAAK,QAAA;EA1BqB,eAAA,OAAA,UAAK;EAvB5B,oBAAA,UAAA,UAAQ,aACL,gBAAW;EApDG,gBAAA,GAAC,mBACX,yBACQ,gBAAgB,4BAAuB,QAAA;;EAmLnD,iBAAA,aAAA,aAAW,UACf,KAAK,wCACb;EAsDQ,gBAAA,UAAA,KAAK,wCACb"}
|
|
@@ -1,20 +1,58 @@
|
|
|
1
1
|
import { Query, QueryClient, QueryFilters, QueryFunctionContext, QueryKey, QueryState } from "@tanstack/query-core";
|
|
2
2
|
//#region src/createPersister.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* A single query as stored by {@link experimental_createQueryPersister}.
|
|
5
|
+
*/
|
|
3
6
|
export interface PersistedQuery {
|
|
7
|
+
/**
|
|
8
|
+
* The `buster` the query was saved with. Entries with a different `buster` are discarded.
|
|
9
|
+
*/
|
|
4
10
|
buster: string;
|
|
11
|
+
/**
|
|
12
|
+
* The hash of the query.
|
|
13
|
+
*/
|
|
5
14
|
queryHash: string;
|
|
15
|
+
/**
|
|
16
|
+
* The key of the query.
|
|
17
|
+
*/
|
|
6
18
|
queryKey: QueryKey;
|
|
19
|
+
/**
|
|
20
|
+
* The state of the query, including its data and when it was last updated.
|
|
21
|
+
*/
|
|
7
22
|
state: QueryState;
|
|
8
23
|
}
|
|
24
|
+
/**
|
|
25
|
+
* A value, or a promise that resolves to it.
|
|
26
|
+
*/
|
|
9
27
|
export type MaybePromise<T> = T | Promise<T>;
|
|
28
|
+
/**
|
|
29
|
+
* A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous
|
|
30
|
+
* or return promises.
|
|
31
|
+
*/
|
|
10
32
|
export interface AsyncStorage<TStorageValue = string> {
|
|
33
|
+
/**
|
|
34
|
+
* Reads the value stored under `key`, or `null`/`undefined` if there is none.
|
|
35
|
+
*/
|
|
11
36
|
getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>;
|
|
37
|
+
/**
|
|
38
|
+
* Stores `value` under `key`.
|
|
39
|
+
*/
|
|
12
40
|
setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>;
|
|
41
|
+
/**
|
|
42
|
+
* Removes the value stored under `key`.
|
|
43
|
+
*/
|
|
13
44
|
removeItem: (key: string) => MaybePromise<void>;
|
|
45
|
+
/**
|
|
46
|
+
* Returns all stored key-value pairs. Required for removing expired entries in bulk.
|
|
47
|
+
*/
|
|
14
48
|
entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>;
|
|
15
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Options for {@link experimental_createQueryPersister}.
|
|
52
|
+
*/
|
|
16
53
|
export interface StoragePersisterOptions<TStorageValue = string> {
|
|
17
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* The storage client used for setting and retrieving items from cache.
|
|
18
56
|
* For SSR pass in `undefined`.
|
|
19
57
|
*/
|
|
20
58
|
storage: AsyncStorage<TStorageValue> | undefined | null;
|
|
@@ -50,7 +88,6 @@ export interface StoragePersisterOptions<TStorageValue = string> {
|
|
|
50
88
|
* If set to `true`, the query will refetch on successful query restoration if the data is stale.
|
|
51
89
|
* If set to `false`, the query will not refetch on successful query restoration.
|
|
52
90
|
* If set to `'always'`, the query will always refetch on successful query restoration.
|
|
53
|
-
*
|
|
54
91
|
* @defaultValue true
|
|
55
92
|
*/
|
|
56
93
|
refetchOnRestore?: boolean | 'always';
|
|
@@ -67,13 +104,17 @@ export declare const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
|
67
104
|
*
|
|
68
105
|
* ```
|
|
69
106
|
* useQuery({
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
107
|
+
* queryKey: ['myKey'],
|
|
108
|
+
* queryFn: fetcher,
|
|
109
|
+
* persister: createPersister({
|
|
110
|
+
* storage: localStorage,
|
|
111
|
+
* }),
|
|
112
|
+
* })
|
|
113
|
+
* ```
|
|
114
|
+
* @param options - The storage to persist to, and the options for serializing, expiring, and
|
|
115
|
+
* filtering persisted queries.
|
|
116
|
+
* @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
|
|
117
|
+
* restore, remove, and garbage collect persisted queries manually.
|
|
77
118
|
*/
|
|
78
119
|
export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters }: StoragePersisterOptions<TStorageValue>): {
|
|
79
120
|
persisterFn: <T, TQueryKey extends QueryKey>(queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>, ctx: QueryFunctionContext<TQueryKey>, query: Query) => Promise<T>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPersister.d.ts","names":[],"sources":["../../src/createPersister.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"createPersister.d.ts","names":[],"sources":["../../src/createPersister.ts"],"mappings":";;;;;iBAkBiB;;;;EAIf;;;;EAIA;;;;EAIA,UAAU;;;;EAIV,OAAO;;;;;YAMG,aAAa,KAAK,IAAI,QAAQ;;;;;iBAMzB,aAAa;;;;EAI5B,UAAU,gBAAgB,aAAa;;;;EAIvC,UAAU,aAAa,OAAO,kBAAkB;;;;EAIhD,aAAa,gBAAgB;;;;EAI7B,gBAAgB,aAAa,OAAO,aAAa,OAAO;;;;;iBAMzC,wBAAwB;;;;;EAKvC,SAAS,aAAa;;;;;EAKtB,aAAa,gBAAgB,mBAAmB,aAAa;;;;;EAK7D,eAAe,cAAc,kBAAkB,aAAa;;;;;EAK5D;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;EAIA,UAAU;;qBAGC;;;;;;;;;;;;;;;;;;;;wBAqBG,kCAAkC,0BAChD,SACA,QACA,QACA,WAGA,aAGA,QACA,kBACA,WACC,wBAAwB;EAgIE,cAAA,GAAG,kBAAkB,UAAQ,UAC5C,SAAS,qBAAqB,eAAe,IAAI,QAAQ,IAAE,KAChE,qBAAqB,YAAU,OAC7B,UAAK,QAAA;EA1BqB,eAAA,OAAA,UAAK;EAvB5B,oBAAA,UAAA,UAAQ,aACL,gBAAW;EApDG,gBAAA,GAAC,mBACX,yBACQ,gBAAgB,4BAAuB,QAAA;;EAmLnD,iBAAA,aAAA,aAAW,UACf,KAAK,wCACb;EAsDQ,gBAAA,UAAA,KAAK,wCACb"}
|
|
@@ -8,15 +8,25 @@ const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
|
8
8
|
*
|
|
9
9
|
* ```
|
|
10
10
|
* useQuery({
|
|
11
|
-
queryKey: ['myKey'],
|
|
12
|
-
queryFn: fetcher,
|
|
13
|
-
persister: createPersister({
|
|
14
|
-
storage: localStorage,
|
|
15
|
-
}),
|
|
16
|
-
})
|
|
17
|
-
```
|
|
11
|
+
* queryKey: ['myKey'],
|
|
12
|
+
* queryFn: fetcher,
|
|
13
|
+
* persister: createPersister({
|
|
14
|
+
* storage: localStorage,
|
|
15
|
+
* }),
|
|
16
|
+
* })
|
|
17
|
+
* ```
|
|
18
|
+
* @param options - The storage to persist to, and the options for serializing, expiring, and
|
|
19
|
+
* filtering persisted queries.
|
|
20
|
+
* @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
|
|
21
|
+
* restore, remove, and garbage collect persisted queries manually.
|
|
18
22
|
*/
|
|
19
23
|
function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters }) {
|
|
24
|
+
/**
|
|
25
|
+
* Checks whether a persisted query should be discarded.
|
|
26
|
+
* @param persistedQuery - The persisted query to check.
|
|
27
|
+
* @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different
|
|
28
|
+
* `buster`.
|
|
29
|
+
*/
|
|
20
30
|
function isExpiredOrBusted(persistedQuery) {
|
|
21
31
|
if (persistedQuery.state.dataUpdatedAt) {
|
|
22
32
|
const expired = Date.now() - persistedQuery.state.dataUpdatedAt > maxAge;
|
|
@@ -26,6 +36,14 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
26
36
|
}
|
|
27
37
|
return true;
|
|
28
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are
|
|
41
|
+
* removed instead.
|
|
42
|
+
* @param queryHash - The hash of the query to read.
|
|
43
|
+
* @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.
|
|
44
|
+
* @returns A promise that resolves with the persisted data, or `undefined` if nothing was
|
|
45
|
+
* restored.
|
|
46
|
+
*/
|
|
29
47
|
async function retrieveQuery(queryHash, afterRestoreMacroTask) {
|
|
30
48
|
if (storage != null) {
|
|
31
49
|
const storageKey = `${prefix}-${queryHash}`;
|
|
@@ -54,6 +72,12 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
54
72
|
}
|
|
55
73
|
}
|
|
56
74
|
}
|
|
75
|
+
/**
|
|
76
|
+
* Persists the query with the given key, if it exists in the client's cache.
|
|
77
|
+
* @param queryKey - The key of the query to persist.
|
|
78
|
+
* @param queryClient - The client whose cache holds the query.
|
|
79
|
+
* @returns A promise that resolves once the query is persisted.
|
|
80
|
+
*/
|
|
57
81
|
async function persistQueryByKey(queryKey, queryClient) {
|
|
58
82
|
if (storage != null) {
|
|
59
83
|
const query = queryClient.getQueryCache().find({ queryKey });
|
|
@@ -61,6 +85,11 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
61
85
|
else if (process.env.NODE_ENV === "development") console.warn("Could not find query to be persisted. QueryKey:", JSON.stringify(queryKey));
|
|
62
86
|
}
|
|
63
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* Writes a query's state, key, hash, and `buster` to storage.
|
|
90
|
+
* @param query - The query to persist.
|
|
91
|
+
* @returns A promise that resolves once the entry is serialized and written.
|
|
92
|
+
*/
|
|
64
93
|
async function persistQuery(query) {
|
|
65
94
|
if (storage != null) {
|
|
66
95
|
const storageKey = `${prefix}-${query.queryHash}`;
|
|
@@ -72,6 +101,14 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
72
101
|
}));
|
|
73
102
|
}
|
|
74
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* The `persister` of a query: restores its data from storage if the query has none yet, otherwise
|
|
106
|
+
* runs `queryFn` and persists the result.
|
|
107
|
+
* @param queryFn - The query's own query function.
|
|
108
|
+
* @param ctx - The context passed to `queryFn`.
|
|
109
|
+
* @param query - The query being fetched.
|
|
110
|
+
* @returns A promise that resolves with the restored or fetched data.
|
|
111
|
+
*/
|
|
75
112
|
async function persisterFn(queryFn, ctx, query) {
|
|
76
113
|
const matchesFilter = filters ? matchQuery(filters, query) : true;
|
|
77
114
|
if (matchesFilter && query.state.data === void 0 && storage != null) {
|
|
@@ -90,6 +127,11 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
90
127
|
});
|
|
91
128
|
return Promise.resolve(queryFnResult);
|
|
92
129
|
}
|
|
130
|
+
/**
|
|
131
|
+
* Removes expired, busted, or unreadable entries from storage. Requires the storage to implement
|
|
132
|
+
* `entries`.
|
|
133
|
+
* @returns A promise that resolves once every entry is checked.
|
|
134
|
+
*/
|
|
93
135
|
async function persisterGc() {
|
|
94
136
|
if (storage === null || storage === void 0 ? void 0 : storage.entries) {
|
|
95
137
|
const storageKeyPrefix = `${prefix}-`;
|
|
@@ -106,6 +148,14 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
106
148
|
}
|
|
107
149
|
} else if (process.env.NODE_ENV === "development") throw new Error("Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.");
|
|
108
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* Restores every persisted query matching `filters` into the client's cache with
|
|
153
|
+
* `queryClient.setQueryData`. Requires the storage to implement `entries`.
|
|
154
|
+
* @param queryClient - The client to restore the queries into.
|
|
155
|
+
* @param filters - The `queryKey` and `exact` filters to match. Without them, every query is
|
|
156
|
+
* restored.
|
|
157
|
+
* @returns A promise that resolves once every entry is checked.
|
|
158
|
+
*/
|
|
109
159
|
async function restoreQueries(queryClient, filters = {}) {
|
|
110
160
|
const { exact, queryKey } = filters;
|
|
111
161
|
if (storage === null || storage === void 0 ? void 0 : storage.entries) {
|
|
@@ -132,6 +182,13 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
132
182
|
}
|
|
133
183
|
} else if (process.env.NODE_ENV === "development") throw new Error("Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.");
|
|
134
184
|
}
|
|
185
|
+
/**
|
|
186
|
+
* Removes every persisted query matching `filters` from storage. Requires the storage to implement
|
|
187
|
+
* `entries`.
|
|
188
|
+
* @param filters - The `queryKey` and `exact` filters to match. Without them, every query is
|
|
189
|
+
* removed.
|
|
190
|
+
* @returns A promise that resolves once every entry is checked.
|
|
191
|
+
*/
|
|
135
192
|
async function removeQueries(filters = {}) {
|
|
136
193
|
const { exact, queryKey } = filters;
|
|
137
194
|
if (storage === null || storage === void 0 ? void 0 : storage.entries) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPersister.js","names":[],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\nexport interface PersistedQuery {\n buster: string\n queryHash: string\n queryKey: QueryKey\n state: QueryState\n}\n\nexport type MaybePromise<T> = T | Promise<T>\n\nexport interface AsyncStorage<TStorageValue = string> {\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n removeItem: (key: string) => MaybePromise<void>\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /** The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n *\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n queryKey: ['myKey'],\n queryFn: fetcher,\n persister: createPersister({\n storage: localStorage,\n }),\n })\n ```\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;AA8EA,MAAa,uBAAuB;;;;;;;;;;;;;;;;AAiBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,WACyC;CACzC,SAAS,kBAAkB,gBAA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aAAa,eAClC,MAAM,IAAI,MACR,gJACF;CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"createPersister.js","names":[],"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\n * The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\n * The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded\n * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * @defaultValue true\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n * queryKey: ['myKey'],\n * queryFn: fetcher,\n * persister: createPersister({\n * storage: localStorage,\n * }),\n * })\n * ```\n * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\n */\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\n */\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\n */\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\n */\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\n */\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\n */\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,WACyC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe,MAAM,eAAe;GAEtC,MAAM,UADW,KAAK,IAAI,IAAI,eAAe,MAAM,gBACxB;GAC3B,MAAM,SAAS,eAAe,WAAW;GAEzC,IAAI,WAAW,QACb,OAAO;GAGT,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;;;CAUA,eAAe,cACb,WACA,uBACA;EACA,IAAI,WAAW,MAAM;GACnB,MAAM,aAAa,GAAG,OAAO,GAAG;GAChC,IAAI;IACF,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