@tanstack/query-persist-client-core 5.0.0-beta.6 → 5.0.0-rc.0
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 +100 -0
- package/build/legacy/createPersister.cjs.map +1 -0
- package/build/legacy/createPersister.d.cts +78 -0
- package/build/legacy/createPersister.d.ts +78 -0
- package/build/legacy/createPersister.js +74 -0
- package/build/legacy/createPersister.js.map +1 -0
- package/build/legacy/index.cjs +3 -1
- package/build/legacy/index.cjs.map +1 -1
- package/build/legacy/index.d.cts +1 -0
- package/build/legacy/index.d.ts +1 -0
- package/build/legacy/index.js +1 -0
- package/build/legacy/index.js.map +1 -1
- package/build/modern/createPersister.cjs +100 -0
- package/build/modern/createPersister.cjs.map +1 -0
- package/build/modern/createPersister.d.cts +78 -0
- package/build/modern/createPersister.d.ts +78 -0
- package/build/modern/createPersister.js +74 -0
- package/build/modern/createPersister.js.map +1 -0
- package/build/modern/index.cjs +3 -1
- package/build/modern/index.cjs.map +1 -1
- package/build/modern/index.d.cts +1 -0
- package/build/modern/index.d.ts +1 -0
- package/build/modern/index.js +1 -0
- package/build/modern/index.js.map +1 -1
- package/package.json +7 -3
- package/src/__tests__/createPersister.test.ts +312 -0
- package/src/createPersister.ts +160 -0
- package/src/index.ts +1 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/createPersister.ts
|
|
21
|
+
var createPersister_exports = {};
|
|
22
|
+
__export(createPersister_exports, {
|
|
23
|
+
PERSISTER_KEY_PREFIX: () => PERSISTER_KEY_PREFIX,
|
|
24
|
+
experimental_createPersister: () => experimental_createPersister
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(createPersister_exports);
|
|
27
|
+
var import_query_core = require("@tanstack/query-core");
|
|
28
|
+
var PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
29
|
+
function experimental_createPersister({
|
|
30
|
+
storage,
|
|
31
|
+
buster = "",
|
|
32
|
+
maxAge = 1e3 * 60 * 60 * 24,
|
|
33
|
+
serialize = JSON.stringify,
|
|
34
|
+
deserialize = JSON.parse,
|
|
35
|
+
prefix = PERSISTER_KEY_PREFIX,
|
|
36
|
+
filters
|
|
37
|
+
}) {
|
|
38
|
+
return async function persisterFn(queryFn, context, query) {
|
|
39
|
+
const storageKey = `${prefix}-${query.queryHash}`;
|
|
40
|
+
const matchesFilter = filters ? (0, import_query_core.matchQuery)(filters, query) : true;
|
|
41
|
+
if (matchesFilter && query.state.data === void 0 && storage != null) {
|
|
42
|
+
try {
|
|
43
|
+
const storedData = await storage.getItem(storageKey);
|
|
44
|
+
if (storedData) {
|
|
45
|
+
const persistedQuery = deserialize(storedData);
|
|
46
|
+
if (persistedQuery.state.dataUpdatedAt) {
|
|
47
|
+
const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt;
|
|
48
|
+
const expired = queryAge > maxAge;
|
|
49
|
+
const busted = persistedQuery.buster !== buster;
|
|
50
|
+
if (expired || busted) {
|
|
51
|
+
await storage.removeItem(storageKey);
|
|
52
|
+
} else {
|
|
53
|
+
setTimeout(() => {
|
|
54
|
+
query.setState({
|
|
55
|
+
dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
|
|
56
|
+
errorUpdatedAt: persistedQuery.state.errorUpdatedAt
|
|
57
|
+
});
|
|
58
|
+
if (query.isStale()) {
|
|
59
|
+
query.fetch();
|
|
60
|
+
}
|
|
61
|
+
}, 0);
|
|
62
|
+
return Promise.resolve(persistedQuery.state.data);
|
|
63
|
+
}
|
|
64
|
+
} else {
|
|
65
|
+
await storage.removeItem(storageKey);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
} catch (err) {
|
|
69
|
+
if (process.env.NODE_ENV === "development") {
|
|
70
|
+
console.error(err);
|
|
71
|
+
console.warn(
|
|
72
|
+
"Encountered an error attempting to restore query cache from persisted location."
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
await storage.removeItem(storageKey);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const queryFnResult = await queryFn(context);
|
|
79
|
+
if (matchesFilter && storage != null) {
|
|
80
|
+
setTimeout(() => {
|
|
81
|
+
storage.setItem(
|
|
82
|
+
storageKey,
|
|
83
|
+
serialize({
|
|
84
|
+
state: query.state,
|
|
85
|
+
queryKey: query.queryKey,
|
|
86
|
+
queryHash: query.queryHash,
|
|
87
|
+
buster
|
|
88
|
+
})
|
|
89
|
+
);
|
|
90
|
+
}, 0);
|
|
91
|
+
}
|
|
92
|
+
return Promise.resolve(queryFnResult);
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
96
|
+
0 && (module.exports = {
|
|
97
|
+
PERSISTER_KEY_PREFIX,
|
|
98
|
+
experimental_createPersister
|
|
99
|
+
});
|
|
100
|
+
//# sourceMappingURL=createPersister.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/createPersister.ts"],"sourcesContent":["import { matchQuery } from '@tanstack/query-core'\nimport type { QueryFilters } from '@tanstack/query-core'\nimport type {\n Query,\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 interface AsyncStorage {\n getItem: (key: string) => Promise<string | undefined | null>\n setItem: (key: string, value: string) => Promise<unknown>\n removeItem: (key: string) => Promise<void>\n}\n\nexport interface StoragePersisterOptions {\n /** The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage | Storage | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => string\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: string) => 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 * 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 persistance.\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_createPersister({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n prefix = PERSISTER_KEY_PREFIX,\n filters,\n}: StoragePersisterOptions) {\n return async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n context: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const storageKey = `${prefix}-${query.queryHash}`\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 try {\n const storedData = await storage.getItem(storageKey)\n if (storedData) {\n const persistedQuery = deserialize(storedData)\n\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 if (expired || busted) {\n await storage.removeItem(storageKey)\n } else {\n // Just after restoring we want to get fresh data from the server if it's stale\n setTimeout(() => {\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 (query.isStale()) {\n query.fetch()\n }\n }, 0)\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return Promise.resolve(persistedQuery.state.data as T)\n }\n } else {\n await storage.removeItem(storageKey)\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 // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(context)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n setTimeout(() => {\n storage.setItem(\n storageKey,\n serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }, 0)\n }\n\n return Promise.resolve(queryFnResult)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAA2B;AA6DpB,IAAM,uBAAuB;AAiB7B,SAAS,6BAA6B;AAAA,EAC3C;AAAA,EACA,SAAS;AAAA,EACT,SAAS,MAAO,KAAK,KAAK;AAAA,EAC1B,YAAY,KAAK;AAAA,EACjB,cAAc,KAAK;AAAA,EACnB,SAAS;AAAA,EACT;AACF,GAA4B;AAC1B,SAAO,eAAe,YACpB,SACA,SACA,OACA;AACA,UAAM,aAAa,GAAG,MAAM,IAAI,MAAM,SAAS;AAC/C,UAAM,gBAAgB,cAAU,8BAAW,SAAS,KAAK,IAAI;AAG7D,QAAI,iBAAiB,MAAM,MAAM,SAAS,UAAa,WAAW,MAAM;AACtE,UAAI;AACF,cAAM,aAAa,MAAM,QAAQ,QAAQ,UAAU;AACnD,YAAI,YAAY;AACd,gBAAM,iBAAiB,YAAY,UAAU;AAE7C,cAAI,eAAe,MAAM,eAAe;AACtC,kBAAM,WAAW,KAAK,IAAI,IAAI,eAAe,MAAM;AACnD,kBAAM,UAAU,WAAW;AAC3B,kBAAM,SAAS,eAAe,WAAW;AACzC,gBAAI,WAAW,QAAQ;AACrB,oBAAM,QAAQ,WAAW,UAAU;AAAA,YACrC,OAAO;AAEL,yBAAW,MAAM;AAEf,sBAAM,SAAS;AAAA,kBACb,eAAe,eAAe,MAAM;AAAA,kBACpC,gBAAgB,eAAe,MAAM;AAAA,gBACvC,CAAC;AAED,oBAAI,MAAM,QAAQ,GAAG;AACnB,wBAAM,MAAM;AAAA,gBACd;AAAA,cACF,GAAG,CAAC;AAEJ,qBAAO,QAAQ,QAAQ,eAAe,MAAM,IAAS;AAAA,YACvD;AAAA,UACF,OAAO;AACL,kBAAM,QAAQ,WAAW,UAAU;AAAA,UACrC;AAAA,QACF;AAAA,MACF,SAAS,KAAK;AACZ,YAAI,QAAQ,IAAI,aAAa,eAAe;AAC1C,kBAAQ,MAAM,GAAG;AACjB,kBAAQ;AAAA,YACN;AAAA,UACF;AAAA,QACF;AACA,cAAM,QAAQ,WAAW,UAAU;AAAA,MACrC;AAAA,IACF;AAGA,UAAM,gBAAgB,MAAM,QAAQ,OAAO;AAE3C,QAAI,iBAAiB,WAAW,MAAM;AAEpC,iBAAW,MAAM;AACf,gBAAQ;AAAA,UACN;AAAA,UACA,UAAU;AAAA,YACR,OAAO,MAAM;AAAA,YACb,UAAU,MAAM;AAAA,YAChB,WAAW,MAAM;AAAA,YACjB;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF,GAAG,CAAC;AAAA,IACN;AAEA,WAAO,QAAQ,QAAQ,aAAa;AAAA,EACtC;AACF;","names":[]}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { QueryKey, QueryState, QueryFilters, Query } from '@tanstack/query-core';
|
|
2
|
+
|
|
3
|
+
interface PersistedQuery {
|
|
4
|
+
buster: string;
|
|
5
|
+
queryHash: string;
|
|
6
|
+
queryKey: QueryKey;
|
|
7
|
+
state: QueryState;
|
|
8
|
+
}
|
|
9
|
+
interface AsyncStorage {
|
|
10
|
+
getItem: (key: string) => Promise<string | undefined | null>;
|
|
11
|
+
setItem: (key: string, value: string) => Promise<unknown>;
|
|
12
|
+
removeItem: (key: string) => Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
interface StoragePersisterOptions {
|
|
15
|
+
/** The storage client used for setting and retrieving items from cache.
|
|
16
|
+
* For SSR pass in `undefined`.
|
|
17
|
+
*/
|
|
18
|
+
storage: AsyncStorage | Storage | undefined | null;
|
|
19
|
+
/**
|
|
20
|
+
* How to serialize the data to storage.
|
|
21
|
+
* @default `JSON.stringify`
|
|
22
|
+
*/
|
|
23
|
+
serialize?: (persistedQuery: PersistedQuery) => string;
|
|
24
|
+
/**
|
|
25
|
+
* How to deserialize the data from storage.
|
|
26
|
+
* @default `JSON.parse`
|
|
27
|
+
*/
|
|
28
|
+
deserialize?: (cachedString: string) => PersistedQuery;
|
|
29
|
+
/**
|
|
30
|
+
* A unique string that can be used to forcefully invalidate existing caches,
|
|
31
|
+
* if they do not share the same buster string
|
|
32
|
+
*/
|
|
33
|
+
buster?: string;
|
|
34
|
+
/**
|
|
35
|
+
* The max-allowed age of the cache in milliseconds.
|
|
36
|
+
* If a persisted cache is found that is older than this
|
|
37
|
+
* time, it will be discarded
|
|
38
|
+
* @default 24 hours
|
|
39
|
+
*/
|
|
40
|
+
maxAge?: number;
|
|
41
|
+
/**
|
|
42
|
+
* Prefix to be used for storage key.
|
|
43
|
+
* Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
|
|
44
|
+
* @default 'tanstack-query'
|
|
45
|
+
*/
|
|
46
|
+
prefix?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Filters to narrow down which Queries should be persisted.
|
|
49
|
+
*/
|
|
50
|
+
filters?: QueryFilters;
|
|
51
|
+
}
|
|
52
|
+
declare const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
53
|
+
/**
|
|
54
|
+
* Warning: experimental feature.
|
|
55
|
+
* This utility function enables fine-grained query persistance.
|
|
56
|
+
* Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.
|
|
57
|
+
*
|
|
58
|
+
* ```
|
|
59
|
+
* useQuery({
|
|
60
|
+
queryKey: ['myKey'],
|
|
61
|
+
queryFn: fetcher,
|
|
62
|
+
persister: createPersister({
|
|
63
|
+
storage: localStorage,
|
|
64
|
+
}),
|
|
65
|
+
})
|
|
66
|
+
```
|
|
67
|
+
*/
|
|
68
|
+
declare function experimental_createPersister({ storage, buster, maxAge, serialize, deserialize, prefix, filters, }: StoragePersisterOptions): <T, TQueryKey extends QueryKey>(queryFn: (context: {
|
|
69
|
+
queryKey: TQueryKey;
|
|
70
|
+
signal: AbortSignal;
|
|
71
|
+
meta: Record<string, unknown> | undefined;
|
|
72
|
+
}) => T | Promise<T>, context: {
|
|
73
|
+
queryKey: TQueryKey;
|
|
74
|
+
signal: AbortSignal;
|
|
75
|
+
meta: Record<string, unknown> | undefined;
|
|
76
|
+
}, query: Query) => Promise<T>;
|
|
77
|
+
|
|
78
|
+
export { AsyncStorage, PERSISTER_KEY_PREFIX, PersistedQuery, StoragePersisterOptions, experimental_createPersister };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { QueryKey, QueryState, QueryFilters, Query } from '@tanstack/query-core';
|
|
2
|
+
|
|
3
|
+
interface PersistedQuery {
|
|
4
|
+
buster: string;
|
|
5
|
+
queryHash: string;
|
|
6
|
+
queryKey: QueryKey;
|
|
7
|
+
state: QueryState;
|
|
8
|
+
}
|
|
9
|
+
interface AsyncStorage {
|
|
10
|
+
getItem: (key: string) => Promise<string | undefined | null>;
|
|
11
|
+
setItem: (key: string, value: string) => Promise<unknown>;
|
|
12
|
+
removeItem: (key: string) => Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
interface StoragePersisterOptions {
|
|
15
|
+
/** The storage client used for setting and retrieving items from cache.
|
|
16
|
+
* For SSR pass in `undefined`.
|
|
17
|
+
*/
|
|
18
|
+
storage: AsyncStorage | Storage | undefined | null;
|
|
19
|
+
/**
|
|
20
|
+
* How to serialize the data to storage.
|
|
21
|
+
* @default `JSON.stringify`
|
|
22
|
+
*/
|
|
23
|
+
serialize?: (persistedQuery: PersistedQuery) => string;
|
|
24
|
+
/**
|
|
25
|
+
* How to deserialize the data from storage.
|
|
26
|
+
* @default `JSON.parse`
|
|
27
|
+
*/
|
|
28
|
+
deserialize?: (cachedString: string) => PersistedQuery;
|
|
29
|
+
/**
|
|
30
|
+
* A unique string that can be used to forcefully invalidate existing caches,
|
|
31
|
+
* if they do not share the same buster string
|
|
32
|
+
*/
|
|
33
|
+
buster?: string;
|
|
34
|
+
/**
|
|
35
|
+
* The max-allowed age of the cache in milliseconds.
|
|
36
|
+
* If a persisted cache is found that is older than this
|
|
37
|
+
* time, it will be discarded
|
|
38
|
+
* @default 24 hours
|
|
39
|
+
*/
|
|
40
|
+
maxAge?: number;
|
|
41
|
+
/**
|
|
42
|
+
* Prefix to be used for storage key.
|
|
43
|
+
* Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
|
|
44
|
+
* @default 'tanstack-query'
|
|
45
|
+
*/
|
|
46
|
+
prefix?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Filters to narrow down which Queries should be persisted.
|
|
49
|
+
*/
|
|
50
|
+
filters?: QueryFilters;
|
|
51
|
+
}
|
|
52
|
+
declare const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
53
|
+
/**
|
|
54
|
+
* Warning: experimental feature.
|
|
55
|
+
* This utility function enables fine-grained query persistance.
|
|
56
|
+
* Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.
|
|
57
|
+
*
|
|
58
|
+
* ```
|
|
59
|
+
* useQuery({
|
|
60
|
+
queryKey: ['myKey'],
|
|
61
|
+
queryFn: fetcher,
|
|
62
|
+
persister: createPersister({
|
|
63
|
+
storage: localStorage,
|
|
64
|
+
}),
|
|
65
|
+
})
|
|
66
|
+
```
|
|
67
|
+
*/
|
|
68
|
+
declare function experimental_createPersister({ storage, buster, maxAge, serialize, deserialize, prefix, filters, }: StoragePersisterOptions): <T, TQueryKey extends QueryKey>(queryFn: (context: {
|
|
69
|
+
queryKey: TQueryKey;
|
|
70
|
+
signal: AbortSignal;
|
|
71
|
+
meta: Record<string, unknown> | undefined;
|
|
72
|
+
}) => T | Promise<T>, context: {
|
|
73
|
+
queryKey: TQueryKey;
|
|
74
|
+
signal: AbortSignal;
|
|
75
|
+
meta: Record<string, unknown> | undefined;
|
|
76
|
+
}, query: Query) => Promise<T>;
|
|
77
|
+
|
|
78
|
+
export { AsyncStorage, PERSISTER_KEY_PREFIX, PersistedQuery, StoragePersisterOptions, experimental_createPersister };
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// src/createPersister.ts
|
|
2
|
+
import { matchQuery } from "@tanstack/query-core";
|
|
3
|
+
var PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
4
|
+
function experimental_createPersister({
|
|
5
|
+
storage,
|
|
6
|
+
buster = "",
|
|
7
|
+
maxAge = 1e3 * 60 * 60 * 24,
|
|
8
|
+
serialize = JSON.stringify,
|
|
9
|
+
deserialize = JSON.parse,
|
|
10
|
+
prefix = PERSISTER_KEY_PREFIX,
|
|
11
|
+
filters
|
|
12
|
+
}) {
|
|
13
|
+
return async function persisterFn(queryFn, context, query) {
|
|
14
|
+
const storageKey = `${prefix}-${query.queryHash}`;
|
|
15
|
+
const matchesFilter = filters ? matchQuery(filters, query) : true;
|
|
16
|
+
if (matchesFilter && query.state.data === void 0 && storage != null) {
|
|
17
|
+
try {
|
|
18
|
+
const storedData = await storage.getItem(storageKey);
|
|
19
|
+
if (storedData) {
|
|
20
|
+
const persistedQuery = deserialize(storedData);
|
|
21
|
+
if (persistedQuery.state.dataUpdatedAt) {
|
|
22
|
+
const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt;
|
|
23
|
+
const expired = queryAge > maxAge;
|
|
24
|
+
const busted = persistedQuery.buster !== buster;
|
|
25
|
+
if (expired || busted) {
|
|
26
|
+
await storage.removeItem(storageKey);
|
|
27
|
+
} else {
|
|
28
|
+
setTimeout(() => {
|
|
29
|
+
query.setState({
|
|
30
|
+
dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
|
|
31
|
+
errorUpdatedAt: persistedQuery.state.errorUpdatedAt
|
|
32
|
+
});
|
|
33
|
+
if (query.isStale()) {
|
|
34
|
+
query.fetch();
|
|
35
|
+
}
|
|
36
|
+
}, 0);
|
|
37
|
+
return Promise.resolve(persistedQuery.state.data);
|
|
38
|
+
}
|
|
39
|
+
} else {
|
|
40
|
+
await storage.removeItem(storageKey);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
} catch (err) {
|
|
44
|
+
if (process.env.NODE_ENV === "development") {
|
|
45
|
+
console.error(err);
|
|
46
|
+
console.warn(
|
|
47
|
+
"Encountered an error attempting to restore query cache from persisted location."
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
await storage.removeItem(storageKey);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const queryFnResult = await queryFn(context);
|
|
54
|
+
if (matchesFilter && storage != null) {
|
|
55
|
+
setTimeout(() => {
|
|
56
|
+
storage.setItem(
|
|
57
|
+
storageKey,
|
|
58
|
+
serialize({
|
|
59
|
+
state: query.state,
|
|
60
|
+
queryKey: query.queryKey,
|
|
61
|
+
queryHash: query.queryHash,
|
|
62
|
+
buster
|
|
63
|
+
})
|
|
64
|
+
);
|
|
65
|
+
}, 0);
|
|
66
|
+
}
|
|
67
|
+
return Promise.resolve(queryFnResult);
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
export {
|
|
71
|
+
PERSISTER_KEY_PREFIX,
|
|
72
|
+
experimental_createPersister
|
|
73
|
+
};
|
|
74
|
+
//# sourceMappingURL=createPersister.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/createPersister.ts"],"sourcesContent":["import { matchQuery } from '@tanstack/query-core'\nimport type { QueryFilters } from '@tanstack/query-core'\nimport type {\n Query,\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 interface AsyncStorage {\n getItem: (key: string) => Promise<string | undefined | null>\n setItem: (key: string, value: string) => Promise<unknown>\n removeItem: (key: string) => Promise<void>\n}\n\nexport interface StoragePersisterOptions {\n /** The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage | Storage | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => string\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: string) => 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 * 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 persistance.\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_createPersister({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n prefix = PERSISTER_KEY_PREFIX,\n filters,\n}: StoragePersisterOptions) {\n return async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n context: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const storageKey = `${prefix}-${query.queryHash}`\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 try {\n const storedData = await storage.getItem(storageKey)\n if (storedData) {\n const persistedQuery = deserialize(storedData)\n\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 if (expired || busted) {\n await storage.removeItem(storageKey)\n } else {\n // Just after restoring we want to get fresh data from the server if it's stale\n setTimeout(() => {\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 (query.isStale()) {\n query.fetch()\n }\n }, 0)\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return Promise.resolve(persistedQuery.state.data as T)\n }\n } else {\n await storage.removeItem(storageKey)\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 // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(context)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n setTimeout(() => {\n storage.setItem(\n storageKey,\n serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }, 0)\n }\n\n return Promise.resolve(queryFnResult)\n }\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AA6DpB,IAAM,uBAAuB;AAiB7B,SAAS,6BAA6B;AAAA,EAC3C;AAAA,EACA,SAAS;AAAA,EACT,SAAS,MAAO,KAAK,KAAK;AAAA,EAC1B,YAAY,KAAK;AAAA,EACjB,cAAc,KAAK;AAAA,EACnB,SAAS;AAAA,EACT;AACF,GAA4B;AAC1B,SAAO,eAAe,YACpB,SACA,SACA,OACA;AACA,UAAM,aAAa,GAAG,MAAM,IAAI,MAAM,SAAS;AAC/C,UAAM,gBAAgB,UAAU,WAAW,SAAS,KAAK,IAAI;AAG7D,QAAI,iBAAiB,MAAM,MAAM,SAAS,UAAa,WAAW,MAAM;AACtE,UAAI;AACF,cAAM,aAAa,MAAM,QAAQ,QAAQ,UAAU;AACnD,YAAI,YAAY;AACd,gBAAM,iBAAiB,YAAY,UAAU;AAE7C,cAAI,eAAe,MAAM,eAAe;AACtC,kBAAM,WAAW,KAAK,IAAI,IAAI,eAAe,MAAM;AACnD,kBAAM,UAAU,WAAW;AAC3B,kBAAM,SAAS,eAAe,WAAW;AACzC,gBAAI,WAAW,QAAQ;AACrB,oBAAM,QAAQ,WAAW,UAAU;AAAA,YACrC,OAAO;AAEL,yBAAW,MAAM;AAEf,sBAAM,SAAS;AAAA,kBACb,eAAe,eAAe,MAAM;AAAA,kBACpC,gBAAgB,eAAe,MAAM;AAAA,gBACvC,CAAC;AAED,oBAAI,MAAM,QAAQ,GAAG;AACnB,wBAAM,MAAM;AAAA,gBACd;AAAA,cACF,GAAG,CAAC;AAEJ,qBAAO,QAAQ,QAAQ,eAAe,MAAM,IAAS;AAAA,YACvD;AAAA,UACF,OAAO;AACL,kBAAM,QAAQ,WAAW,UAAU;AAAA,UACrC;AAAA,QACF;AAAA,MACF,SAAS,KAAK;AACZ,YAAI,QAAQ,IAAI,aAAa,eAAe;AAC1C,kBAAQ,MAAM,GAAG;AACjB,kBAAQ;AAAA,YACN;AAAA,UACF;AAAA,QACF;AACA,cAAM,QAAQ,WAAW,UAAU;AAAA,MACrC;AAAA,IACF;AAGA,UAAM,gBAAgB,MAAM,QAAQ,OAAO;AAE3C,QAAI,iBAAiB,WAAW,MAAM;AAEpC,iBAAW,MAAM;AACf,gBAAQ;AAAA,UACN;AAAA,UACA,UAAU;AAAA,YACR,OAAO,MAAM;AAAA,YACb,UAAU,MAAM;AAAA,YAChB,WAAW,MAAM;AAAA,YACjB;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF,GAAG,CAAC;AAAA,IACN;AAEA,WAAO,QAAQ,QAAQ,aAAa;AAAA,EACtC;AACF;","names":[]}
|
package/build/legacy/index.cjs
CHANGED
|
@@ -19,9 +19,11 @@ var src_exports = {};
|
|
|
19
19
|
module.exports = __toCommonJS(src_exports);
|
|
20
20
|
__reExport(src_exports, require("./persist.cjs"), module.exports);
|
|
21
21
|
__reExport(src_exports, require("./retryStrategies.cjs"), module.exports);
|
|
22
|
+
__reExport(src_exports, require("./createPersister.cjs"), module.exports);
|
|
22
23
|
// Annotate the CommonJS export names for ESM import in node:
|
|
23
24
|
0 && (module.exports = {
|
|
24
25
|
...require("./persist.cjs"),
|
|
25
|
-
...require("./retryStrategies.cjs")
|
|
26
|
+
...require("./retryStrategies.cjs"),
|
|
27
|
+
...require("./createPersister.cjs")
|
|
26
28
|
});
|
|
27
29
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport * from './persist'\nexport * from './retryStrategies'\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AAAA;AAEA,wBAAc,0BAFd;AAGA,wBAAc,kCAHd;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport * from './persist'\nexport * from './retryStrategies'\nexport * from './createPersister'\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AAAA;AAEA,wBAAc,0BAFd;AAGA,wBAAc,kCAHd;AAIA,wBAAc,kCAJd;","names":[]}
|
package/build/legacy/index.d.cts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { PersistQueryClienRootOptions, PersistQueryClientOptions, PersistedClient, PersistedQueryClientRestoreOptions, PersistedQueryClientSaveOptions, Persister, Promisable, persistQueryClient, persistQueryClientRestore, persistQueryClientSave, persistQueryClientSubscribe } from './persist.cjs';
|
|
2
2
|
export { PersistRetryer, removeOldestQuery } from './retryStrategies.cjs';
|
|
3
|
+
export { AsyncStorage, PERSISTER_KEY_PREFIX, PersistedQuery, StoragePersisterOptions, experimental_createPersister } from './createPersister.cjs';
|
|
3
4
|
import '@tanstack/query-core';
|
package/build/legacy/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { PersistQueryClienRootOptions, PersistQueryClientOptions, PersistedClient, PersistedQueryClientRestoreOptions, PersistedQueryClientSaveOptions, Persister, Promisable, persistQueryClient, persistQueryClientRestore, persistQueryClientSave, persistQueryClientSubscribe } from './persist.js';
|
|
2
2
|
export { PersistRetryer, removeOldestQuery } from './retryStrategies.js';
|
|
3
|
+
export { AsyncStorage, PERSISTER_KEY_PREFIX, PersistedQuery, StoragePersisterOptions, experimental_createPersister } from './createPersister.js';
|
|
3
4
|
import '@tanstack/query-core';
|
package/build/legacy/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport * from './persist'\nexport * from './retryStrategies'\n"],"mappings":";AAEA,cAAc;AACd,cAAc;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport * from './persist'\nexport * from './retryStrategies'\nexport * from './createPersister'\n"],"mappings":";AAEA,cAAc;AACd,cAAc;AACd,cAAc;","names":[]}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/createPersister.ts
|
|
21
|
+
var createPersister_exports = {};
|
|
22
|
+
__export(createPersister_exports, {
|
|
23
|
+
PERSISTER_KEY_PREFIX: () => PERSISTER_KEY_PREFIX,
|
|
24
|
+
experimental_createPersister: () => experimental_createPersister
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(createPersister_exports);
|
|
27
|
+
var import_query_core = require("@tanstack/query-core");
|
|
28
|
+
var PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
29
|
+
function experimental_createPersister({
|
|
30
|
+
storage,
|
|
31
|
+
buster = "",
|
|
32
|
+
maxAge = 1e3 * 60 * 60 * 24,
|
|
33
|
+
serialize = JSON.stringify,
|
|
34
|
+
deserialize = JSON.parse,
|
|
35
|
+
prefix = PERSISTER_KEY_PREFIX,
|
|
36
|
+
filters
|
|
37
|
+
}) {
|
|
38
|
+
return async function persisterFn(queryFn, context, query) {
|
|
39
|
+
const storageKey = `${prefix}-${query.queryHash}`;
|
|
40
|
+
const matchesFilter = filters ? (0, import_query_core.matchQuery)(filters, query) : true;
|
|
41
|
+
if (matchesFilter && query.state.data === void 0 && storage != null) {
|
|
42
|
+
try {
|
|
43
|
+
const storedData = await storage.getItem(storageKey);
|
|
44
|
+
if (storedData) {
|
|
45
|
+
const persistedQuery = deserialize(storedData);
|
|
46
|
+
if (persistedQuery.state.dataUpdatedAt) {
|
|
47
|
+
const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt;
|
|
48
|
+
const expired = queryAge > maxAge;
|
|
49
|
+
const busted = persistedQuery.buster !== buster;
|
|
50
|
+
if (expired || busted) {
|
|
51
|
+
await storage.removeItem(storageKey);
|
|
52
|
+
} else {
|
|
53
|
+
setTimeout(() => {
|
|
54
|
+
query.setState({
|
|
55
|
+
dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
|
|
56
|
+
errorUpdatedAt: persistedQuery.state.errorUpdatedAt
|
|
57
|
+
});
|
|
58
|
+
if (query.isStale()) {
|
|
59
|
+
query.fetch();
|
|
60
|
+
}
|
|
61
|
+
}, 0);
|
|
62
|
+
return Promise.resolve(persistedQuery.state.data);
|
|
63
|
+
}
|
|
64
|
+
} else {
|
|
65
|
+
await storage.removeItem(storageKey);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
} catch (err) {
|
|
69
|
+
if (process.env.NODE_ENV === "development") {
|
|
70
|
+
console.error(err);
|
|
71
|
+
console.warn(
|
|
72
|
+
"Encountered an error attempting to restore query cache from persisted location."
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
await storage.removeItem(storageKey);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const queryFnResult = await queryFn(context);
|
|
79
|
+
if (matchesFilter && storage != null) {
|
|
80
|
+
setTimeout(() => {
|
|
81
|
+
storage.setItem(
|
|
82
|
+
storageKey,
|
|
83
|
+
serialize({
|
|
84
|
+
state: query.state,
|
|
85
|
+
queryKey: query.queryKey,
|
|
86
|
+
queryHash: query.queryHash,
|
|
87
|
+
buster
|
|
88
|
+
})
|
|
89
|
+
);
|
|
90
|
+
}, 0);
|
|
91
|
+
}
|
|
92
|
+
return Promise.resolve(queryFnResult);
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
96
|
+
0 && (module.exports = {
|
|
97
|
+
PERSISTER_KEY_PREFIX,
|
|
98
|
+
experimental_createPersister
|
|
99
|
+
});
|
|
100
|
+
//# sourceMappingURL=createPersister.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/createPersister.ts"],"sourcesContent":["import { matchQuery } from '@tanstack/query-core'\nimport type { QueryFilters } from '@tanstack/query-core'\nimport type {\n Query,\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 interface AsyncStorage {\n getItem: (key: string) => Promise<string | undefined | null>\n setItem: (key: string, value: string) => Promise<unknown>\n removeItem: (key: string) => Promise<void>\n}\n\nexport interface StoragePersisterOptions {\n /** The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage | Storage | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => string\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: string) => 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 * 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 persistance.\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_createPersister({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n prefix = PERSISTER_KEY_PREFIX,\n filters,\n}: StoragePersisterOptions) {\n return async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n context: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const storageKey = `${prefix}-${query.queryHash}`\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 try {\n const storedData = await storage.getItem(storageKey)\n if (storedData) {\n const persistedQuery = deserialize(storedData)\n\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 if (expired || busted) {\n await storage.removeItem(storageKey)\n } else {\n // Just after restoring we want to get fresh data from the server if it's stale\n setTimeout(() => {\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 (query.isStale()) {\n query.fetch()\n }\n }, 0)\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return Promise.resolve(persistedQuery.state.data as T)\n }\n } else {\n await storage.removeItem(storageKey)\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 // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(context)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n setTimeout(() => {\n storage.setItem(\n storageKey,\n serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }, 0)\n }\n\n return Promise.resolve(queryFnResult)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAA2B;AA6DpB,IAAM,uBAAuB;AAiB7B,SAAS,6BAA6B;AAAA,EAC3C;AAAA,EACA,SAAS;AAAA,EACT,SAAS,MAAO,KAAK,KAAK;AAAA,EAC1B,YAAY,KAAK;AAAA,EACjB,cAAc,KAAK;AAAA,EACnB,SAAS;AAAA,EACT;AACF,GAA4B;AAC1B,SAAO,eAAe,YACpB,SACA,SACA,OACA;AACA,UAAM,aAAa,GAAG,MAAM,IAAI,MAAM,SAAS;AAC/C,UAAM,gBAAgB,cAAU,8BAAW,SAAS,KAAK,IAAI;AAG7D,QAAI,iBAAiB,MAAM,MAAM,SAAS,UAAa,WAAW,MAAM;AACtE,UAAI;AACF,cAAM,aAAa,MAAM,QAAQ,QAAQ,UAAU;AACnD,YAAI,YAAY;AACd,gBAAM,iBAAiB,YAAY,UAAU;AAE7C,cAAI,eAAe,MAAM,eAAe;AACtC,kBAAM,WAAW,KAAK,IAAI,IAAI,eAAe,MAAM;AACnD,kBAAM,UAAU,WAAW;AAC3B,kBAAM,SAAS,eAAe,WAAW;AACzC,gBAAI,WAAW,QAAQ;AACrB,oBAAM,QAAQ,WAAW,UAAU;AAAA,YACrC,OAAO;AAEL,yBAAW,MAAM;AAEf,sBAAM,SAAS;AAAA,kBACb,eAAe,eAAe,MAAM;AAAA,kBACpC,gBAAgB,eAAe,MAAM;AAAA,gBACvC,CAAC;AAED,oBAAI,MAAM,QAAQ,GAAG;AACnB,wBAAM,MAAM;AAAA,gBACd;AAAA,cACF,GAAG,CAAC;AAEJ,qBAAO,QAAQ,QAAQ,eAAe,MAAM,IAAS;AAAA,YACvD;AAAA,UACF,OAAO;AACL,kBAAM,QAAQ,WAAW,UAAU;AAAA,UACrC;AAAA,QACF;AAAA,MACF,SAAS,KAAK;AACZ,YAAI,QAAQ,IAAI,aAAa,eAAe;AAC1C,kBAAQ,MAAM,GAAG;AACjB,kBAAQ;AAAA,YACN;AAAA,UACF;AAAA,QACF;AACA,cAAM,QAAQ,WAAW,UAAU;AAAA,MACrC;AAAA,IACF;AAGA,UAAM,gBAAgB,MAAM,QAAQ,OAAO;AAE3C,QAAI,iBAAiB,WAAW,MAAM;AAEpC,iBAAW,MAAM;AACf,gBAAQ;AAAA,UACN;AAAA,UACA,UAAU;AAAA,YACR,OAAO,MAAM;AAAA,YACb,UAAU,MAAM;AAAA,YAChB,WAAW,MAAM;AAAA,YACjB;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF,GAAG,CAAC;AAAA,IACN;AAEA,WAAO,QAAQ,QAAQ,aAAa;AAAA,EACtC;AACF;","names":[]}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { QueryKey, QueryState, QueryFilters, Query } from '@tanstack/query-core';
|
|
2
|
+
|
|
3
|
+
interface PersistedQuery {
|
|
4
|
+
buster: string;
|
|
5
|
+
queryHash: string;
|
|
6
|
+
queryKey: QueryKey;
|
|
7
|
+
state: QueryState;
|
|
8
|
+
}
|
|
9
|
+
interface AsyncStorage {
|
|
10
|
+
getItem: (key: string) => Promise<string | undefined | null>;
|
|
11
|
+
setItem: (key: string, value: string) => Promise<unknown>;
|
|
12
|
+
removeItem: (key: string) => Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
interface StoragePersisterOptions {
|
|
15
|
+
/** The storage client used for setting and retrieving items from cache.
|
|
16
|
+
* For SSR pass in `undefined`.
|
|
17
|
+
*/
|
|
18
|
+
storage: AsyncStorage | Storage | undefined | null;
|
|
19
|
+
/**
|
|
20
|
+
* How to serialize the data to storage.
|
|
21
|
+
* @default `JSON.stringify`
|
|
22
|
+
*/
|
|
23
|
+
serialize?: (persistedQuery: PersistedQuery) => string;
|
|
24
|
+
/**
|
|
25
|
+
* How to deserialize the data from storage.
|
|
26
|
+
* @default `JSON.parse`
|
|
27
|
+
*/
|
|
28
|
+
deserialize?: (cachedString: string) => PersistedQuery;
|
|
29
|
+
/**
|
|
30
|
+
* A unique string that can be used to forcefully invalidate existing caches,
|
|
31
|
+
* if they do not share the same buster string
|
|
32
|
+
*/
|
|
33
|
+
buster?: string;
|
|
34
|
+
/**
|
|
35
|
+
* The max-allowed age of the cache in milliseconds.
|
|
36
|
+
* If a persisted cache is found that is older than this
|
|
37
|
+
* time, it will be discarded
|
|
38
|
+
* @default 24 hours
|
|
39
|
+
*/
|
|
40
|
+
maxAge?: number;
|
|
41
|
+
/**
|
|
42
|
+
* Prefix to be used for storage key.
|
|
43
|
+
* Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
|
|
44
|
+
* @default 'tanstack-query'
|
|
45
|
+
*/
|
|
46
|
+
prefix?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Filters to narrow down which Queries should be persisted.
|
|
49
|
+
*/
|
|
50
|
+
filters?: QueryFilters;
|
|
51
|
+
}
|
|
52
|
+
declare const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
53
|
+
/**
|
|
54
|
+
* Warning: experimental feature.
|
|
55
|
+
* This utility function enables fine-grained query persistance.
|
|
56
|
+
* Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.
|
|
57
|
+
*
|
|
58
|
+
* ```
|
|
59
|
+
* useQuery({
|
|
60
|
+
queryKey: ['myKey'],
|
|
61
|
+
queryFn: fetcher,
|
|
62
|
+
persister: createPersister({
|
|
63
|
+
storage: localStorage,
|
|
64
|
+
}),
|
|
65
|
+
})
|
|
66
|
+
```
|
|
67
|
+
*/
|
|
68
|
+
declare function experimental_createPersister({ storage, buster, maxAge, serialize, deserialize, prefix, filters, }: StoragePersisterOptions): <T, TQueryKey extends QueryKey>(queryFn: (context: {
|
|
69
|
+
queryKey: TQueryKey;
|
|
70
|
+
signal: AbortSignal;
|
|
71
|
+
meta: Record<string, unknown> | undefined;
|
|
72
|
+
}) => T | Promise<T>, context: {
|
|
73
|
+
queryKey: TQueryKey;
|
|
74
|
+
signal: AbortSignal;
|
|
75
|
+
meta: Record<string, unknown> | undefined;
|
|
76
|
+
}, query: Query) => Promise<T>;
|
|
77
|
+
|
|
78
|
+
export { AsyncStorage, PERSISTER_KEY_PREFIX, PersistedQuery, StoragePersisterOptions, experimental_createPersister };
|