@choksheak/react-utils 0.4.0 → 0.4.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/NoSSR.cjs +1 -1
- package/NoSSR.d.ts +7 -3
- package/NoSSR.min.cjs +1 -1
- package/NoSSR.min.mjs +1 -1
- package/NoSSR.mjs +1 -1
- package/{chunk-33UMQLKY.mjs → chunk-4235I4VO.mjs} +1 -10
- package/{chunk-GPV6JIQK.mjs → chunk-4J7TN5JN.mjs} +1 -1
- package/chunk-BBCGQMWI.min.cjs +2 -0
- package/chunk-BBCGQMWI.min.cjs.map +1 -0
- package/{chunk-5DO7KC3L.cjs → chunk-CYTO5EZE.cjs} +2 -11
- package/chunk-GKNOICX3.cjs +561 -0
- package/chunk-HRE7YPUJ.min.mjs +2 -0
- package/chunk-IS3BZTWE.cjs +35 -0
- package/chunk-JOHZV3FD.min.cjs +2 -0
- package/{chunk-F5L32IUC.min.cjs.map → chunk-JOHZV3FD.min.cjs.map} +1 -1
- package/chunk-KGN4HQPP.min.cjs +2 -0
- package/chunk-KGN4HQPP.min.cjs.map +1 -0
- package/chunk-NL4FU2MJ.min.mjs +2 -0
- package/chunk-NL4FU2MJ.min.mjs.map +1 -0
- package/chunk-R7POPVJR.mjs +35 -0
- package/chunk-TI3FMEYP.min.mjs +2 -0
- package/{chunk-RM4ZGGZ2.min.mjs.map → chunk-TI3FMEYP.min.mjs.map} +1 -1
- package/chunk-U7RD7B3N.min.mjs +2 -0
- package/chunk-U7RD7B3N.min.mjs.map +1 -0
- package/{chunk-WVLPJPWG.cjs → chunk-WXLUEDBO.cjs} +3 -3
- package/chunk-X6EKF4N7.mjs +561 -0
- package/chunk-ZCDXPV3A.min.cjs +2 -0
- package/chunk-ZCDXPV3A.min.cjs.map +1 -0
- package/dist-O6NNX4Y3.min.mjs +2 -0
- package/dist-O6NNX4Y3.min.mjs.map +1 -0
- package/dist-SEGTJ72R.min.cjs +2 -0
- package/dist-SEGTJ72R.min.cjs.map +1 -0
- package/dist-UKP7SPWZ.cjs +545 -0
- package/dist-YXYQDOH5.mjs +545 -0
- package/index.cjs +43 -0
- package/index.d.cts +8 -0
- package/index.d.ts +8 -0
- package/index.min.cjs +2 -0
- package/index.min.cjs.map +1 -0
- package/index.min.mjs +2 -0
- package/index.mjs +43 -0
- package/magic-string.es-5QZEPJXJ.min.mjs +14 -0
- package/magic-string.es-5QZEPJXJ.min.mjs.map +1 -0
- package/magic-string.es-EREYSDLL.mjs +1308 -0
- package/magic-string.es-FXUUD55Y.min.cjs +14 -0
- package/magic-string.es-FXUUD55Y.min.cjs.map +1 -0
- package/magic-string.es-HC5PDAU3.cjs +1308 -0
- package/package.json +73 -204
- package/sharedQuery.cjs +7 -553
- package/{sharedQuery.d.mts → sharedQuery.d.cts} +5 -4
- package/sharedQuery.d.ts +26 -19
- package/sharedQuery.min.cjs +1 -1
- package/sharedQuery.min.cjs.map +1 -1
- package/sharedQuery.min.mjs +1 -1
- package/sharedQuery.min.mjs.map +1 -1
- package/sharedQuery.mjs +9 -555
- package/sharedState.cjs +1 -1
- package/{sharedState.d.mts → sharedState.d.cts} +1 -1
- package/sharedState.d.ts +17 -11
- package/sharedState.min.cjs +1 -1
- package/sharedState.min.mjs +1 -1
- package/sharedState.mjs +1 -1
- package/storage.cjs +1 -1
- package/storage.d.ts +13 -9
- package/storage.min.cjs +1 -1
- package/storage.min.mjs +1 -1
- package/storage.mjs +1 -1
- package/stringify.cjs +3 -5
- package/stringify.d.ts +3 -1
- package/stringify.min.cjs +1 -1
- package/stringify.min.cjs.map +1 -1
- package/stringify.min.mjs +1 -1
- package/stringify.mjs +2 -4
- package/useDeepMemo.cjs +3 -3
- package/useDeepMemo.d.ts +3 -1
- package/useDeepMemo.min.cjs +1 -1
- package/useDeepMemo.min.mjs +1 -1
- package/useDeepMemo.mjs +2 -2
- package/chunk-3V7WBGWQ.mjs +0 -16
- package/chunk-6ZZ54XM5.min.mjs +0 -2
- package/chunk-6ZZ54XM5.min.mjs.map +0 -1
- package/chunk-74BS2FAO.cjs +0 -12
- package/chunk-F5L32IUC.min.cjs +0 -2
- package/chunk-KE3RXVMS.min.cjs +0 -2
- package/chunk-KE3RXVMS.min.cjs.map +0 -1
- package/chunk-MWDH7YON.min.mjs +0 -2
- package/chunk-O3RBYG3W.min.cjs +0 -2
- package/chunk-O3RBYG3W.min.cjs.map +0 -1
- package/chunk-RM4ZGGZ2.min.mjs +0 -2
- package/chunk-TEZPF6BG.min.cjs +0 -2
- package/chunk-TEZPF6BG.min.cjs.map +0 -1
- package/chunk-UFJNJ3WV.cjs +0 -16
- package/chunk-V7L3UICC.min.mjs +0 -2
- package/chunk-V7L3UICC.min.mjs.map +0 -1
- package/chunk-X6BYQHVC.mjs +0 -12
- package/fetcher.cjs +0 -9
- package/fetcher.d.mts +0 -36
- package/fetcher.d.ts +0 -32
- package/fetcher.min.cjs +0 -2
- package/fetcher.min.cjs.map +0 -1
- package/fetcher.min.mjs +0 -2
- package/fetcher.mjs +0 -9
- /package/{NoSSR.d.mts → NoSSR.d.cts} +0 -0
- /package/{chunk-MWDH7YON.min.mjs.map → chunk-HRE7YPUJ.min.mjs.map} +0 -0
- /package/{fetcher.min.mjs.map → index.min.mjs.map} +0 -0
- /package/{storage.d.mts → storage.d.cts} +0 -0
- /package/{stringify.d.mts → stringify.d.cts} +0 -0
- /package/{useDeepMemo.d.mts → useDeepMemo.d.cts} +0 -0
package/sharedQuery.cjs
CHANGED
|
@@ -1,563 +1,17 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var _chunkUFJNJ3WVcjs = require('./chunk-UFJNJ3WV.cjs');
|
|
4
3
|
|
|
5
4
|
|
|
6
5
|
|
|
7
|
-
var
|
|
6
|
+
var _chunkGKNOICX3cjs = require('./chunk-GKNOICX3.cjs');
|
|
7
|
+
require('./chunk-3X25NN6X.cjs');
|
|
8
8
|
require('./chunk-5PDGU37E.cjs');
|
|
9
|
+
require('./chunk-CYTO5EZE.cjs');
|
|
10
|
+
require('./chunk-WXLUEDBO.cjs');
|
|
11
|
+
require('./chunk-IS3BZTWE.cjs');
|
|
9
12
|
|
|
10
13
|
|
|
11
14
|
|
|
12
|
-
var _chunk5DO7KC3Lcjs = require('./chunk-5DO7KC3L.cjs');
|
|
13
15
|
|
|
14
16
|
|
|
15
|
-
|
|
16
|
-
require('./chunk-74BS2FAO.cjs');
|
|
17
|
-
|
|
18
|
-
// src/sharedQuery.ts
|
|
19
|
-
var _objectsizeof = require('object-sizeof'); var _objectsizeof2 = _interopRequireDefault(_objectsizeof);
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
var _react = require('react');
|
|
27
|
-
var _xxhashjs = require('xxhashjs'); var _xxhashjs2 = _interopRequireDefault(_xxhashjs);
|
|
28
|
-
_chunk5DO7KC3Lcjs.init_stringify.call(void 0, );
|
|
29
|
-
var SharedQueryConfig = {
|
|
30
|
-
/** Refetch on every page load. */
|
|
31
|
-
staleMs: 0,
|
|
32
|
-
/** Keep in cache for a long time. */
|
|
33
|
-
expiryMs: 30 * 864e5,
|
|
34
|
-
/** Always refetch automatically if the data is stale. */
|
|
35
|
-
refetchOnStale: true,
|
|
36
|
-
/** No default persistence configured. */
|
|
37
|
-
persistTo: void 0,
|
|
38
|
-
/** 100 is not too large, but please tweak accordingly. */
|
|
39
|
-
maxSize: 100,
|
|
40
|
-
/** 100kb limit before discarding old records. */
|
|
41
|
-
maxBytes: 1e5,
|
|
42
|
-
/** Default to log to console. */
|
|
43
|
-
log: (...args) => console.log("[sharedQuery]", ...args)
|
|
44
|
-
};
|
|
45
|
-
function configureSharedQuery(config) {
|
|
46
|
-
Object.assign(SharedQueryConfig, config);
|
|
47
|
-
}
|
|
48
|
-
var seenQueryNames = /* @__PURE__ */ new Set();
|
|
49
|
-
function sharedQuery(options) {
|
|
50
|
-
const url = options.url || "";
|
|
51
|
-
const queryName = options.queryName || url;
|
|
52
|
-
if (!queryName) {
|
|
53
|
-
throw new Error(`Either queryName or url must be specified.`);
|
|
54
|
-
}
|
|
55
|
-
if (seenQueryNames.has(queryName)) {
|
|
56
|
-
throw new Error(`Duplicate shared query name "${queryName}"`);
|
|
57
|
-
}
|
|
58
|
-
seenQueryNames.add(queryName);
|
|
59
|
-
const inflightQueries = /* @__PURE__ */ new Map();
|
|
60
|
-
const mountedKeys = /* @__PURE__ */ new Map();
|
|
61
|
-
let queryFn;
|
|
62
|
-
if (options.queryFn) {
|
|
63
|
-
queryFn = options.queryFn;
|
|
64
|
-
} else if (url) {
|
|
65
|
-
queryFn = (...args) => {
|
|
66
|
-
let params = "";
|
|
67
|
-
const firstArg = _optionalChain([args, 'optionalAccess', _ => _[0]]);
|
|
68
|
-
if (firstArg) {
|
|
69
|
-
if (typeof firstArg === "string") {
|
|
70
|
-
params = firstArg;
|
|
71
|
-
} else if (typeof firstArg === "object") {
|
|
72
|
-
const entries = [];
|
|
73
|
-
for (const [k, v] of Object.entries(firstArg)) {
|
|
74
|
-
if (v === void 0) continue;
|
|
75
|
-
if (Array.isArray(v)) {
|
|
76
|
-
for (const item of v) {
|
|
77
|
-
if (item === void 0) continue;
|
|
78
|
-
entries.push([k, String(item)]);
|
|
79
|
-
}
|
|
80
|
-
} else {
|
|
81
|
-
entries.push([k, String(v)]);
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
params = new URLSearchParams(entries).toString();
|
|
85
|
-
}
|
|
86
|
-
if (params) {
|
|
87
|
-
if (url.includes("?")) {
|
|
88
|
-
params = "&" + params;
|
|
89
|
-
} else {
|
|
90
|
-
params = "?" + params;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
return _chunkUFJNJ3WVcjs.fetcher.url(url + params).get().json();
|
|
95
|
-
};
|
|
96
|
-
} else {
|
|
97
|
-
throw new Error(`Either queryFn or url must be specified`);
|
|
98
|
-
}
|
|
99
|
-
const refetchFn = options.refetchFn;
|
|
100
|
-
const staleMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.staleMs]), () => ( SharedQueryConfig.staleMs));
|
|
101
|
-
const expiryMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _3 => _3.expiryMs]), () => ( SharedQueryConfig.expiryMs));
|
|
102
|
-
const refetchOnStale = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _4 => _4.refetchOnStale]), () => ( SharedQueryConfig.refetchOnStale));
|
|
103
|
-
const store = options.store;
|
|
104
|
-
if (store) {
|
|
105
|
-
if ("persistTo" in store && store.isValid) {
|
|
106
|
-
const isValid = store.isValid;
|
|
107
|
-
options = {
|
|
108
|
-
...options,
|
|
109
|
-
store: {
|
|
110
|
-
...store,
|
|
111
|
-
isValid: (u) => {
|
|
112
|
-
if (!u || typeof u !== "object") {
|
|
113
|
-
return false;
|
|
114
|
-
}
|
|
115
|
-
for (const v of Object.values(u)) {
|
|
116
|
-
if (!v || typeof v !== "object" || !("data" in v) || !("dataUpdatedMs" in v) || !("lastUpdatedMs" in v) || typeof v.dataUpdatedMs !== "number" || typeof v.lastUpdatedMs !== "number" || !isValid(v.data)) {
|
|
117
|
-
return false;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
return true;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
} else {
|
|
126
|
-
const persistTo = _nullishCoalesce(options.persistTo, () => ( SharedQueryConfig.persistTo));
|
|
127
|
-
if (persistTo) {
|
|
128
|
-
options = {
|
|
129
|
-
...options,
|
|
130
|
-
store: {
|
|
131
|
-
persistTo,
|
|
132
|
-
key: queryName,
|
|
133
|
-
expiryMs
|
|
134
|
-
}
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
const maxSize = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _5 => _5.maxSize]), () => ( SharedQueryConfig.maxSize));
|
|
139
|
-
const maxBytes = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _6 => _6.maxBytes]), () => ( SharedQueryConfig.maxBytes));
|
|
140
|
-
const keepLastNonEmptyData = Boolean(_optionalChain([options, 'optionalAccess', _7 => _7.keepLastNonEmptyData]));
|
|
141
|
-
const log = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _8 => _8.log]), () => ( SharedQueryConfig.log));
|
|
142
|
-
const queryState = _chunk3X25NN6Xcjs.sharedState.call(void 0,
|
|
143
|
-
{},
|
|
144
|
-
// defaultValue
|
|
145
|
-
options
|
|
146
|
-
);
|
|
147
|
-
function isStale(dataUpdatedMs) {
|
|
148
|
-
if (staleMs === 0) return true;
|
|
149
|
-
const ageMs = Date.now() - dataUpdatedMs;
|
|
150
|
-
return ageMs > staleMs;
|
|
151
|
-
}
|
|
152
|
-
function isExpired(dataUpdatedMs) {
|
|
153
|
-
if (expiryMs === 0) return false;
|
|
154
|
-
const ageMs = Date.now() - dataUpdatedMs;
|
|
155
|
-
return ageMs > expiryMs;
|
|
156
|
-
}
|
|
157
|
-
function enforceSizeLimit() {
|
|
158
|
-
if (!maxSize && !maxBytes) {
|
|
159
|
-
return;
|
|
160
|
-
}
|
|
161
|
-
const oldState = queryState.getSnapshot();
|
|
162
|
-
const oldSize = Object.keys(oldState).length;
|
|
163
|
-
if (oldSize <= 1) {
|
|
164
|
-
return;
|
|
165
|
-
}
|
|
166
|
-
const oldByteSize = _objectsizeof2.default.call(void 0, oldState);
|
|
167
|
-
let numToCut = maxSize ? oldSize - maxSize : 0;
|
|
168
|
-
let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;
|
|
169
|
-
if (numToCut <= 0 && bytesToCut <= 0) {
|
|
170
|
-
log(
|
|
171
|
-
`No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
|
|
172
|
-
);
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
log(
|
|
176
|
-
`Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`
|
|
177
|
-
);
|
|
178
|
-
const newState = { ...oldState };
|
|
179
|
-
let needUpdate = false;
|
|
180
|
-
const deleteKeyIfNotMounted = (key, expired) => {
|
|
181
|
-
if (mountedKeys.has(key)) {
|
|
182
|
-
log(`Cannot clean up ${key} as it is mounted`);
|
|
183
|
-
return;
|
|
184
|
-
}
|
|
185
|
-
const byteSize = _objectsizeof2.default.call(void 0, key) + _objectsizeof2.default.call(void 0, newState[key]);
|
|
186
|
-
log(
|
|
187
|
-
`Cleaning up unmounted${expired ? ", expired" : ""} ${key} (byteSize=${byteSize.toLocaleString()})`
|
|
188
|
-
);
|
|
189
|
-
numToCut--;
|
|
190
|
-
bytesToCut -= byteSize;
|
|
191
|
-
delete newState[key];
|
|
192
|
-
needUpdate = true;
|
|
193
|
-
};
|
|
194
|
-
let entriesByTimeAscending = Object.entries(newState).sort(
|
|
195
|
-
(entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
|
|
196
|
-
);
|
|
197
|
-
for (const [key] of entriesByTimeAscending) {
|
|
198
|
-
if (!isExpired(newState[key].lastUpdatedMs)) {
|
|
199
|
-
break;
|
|
200
|
-
}
|
|
201
|
-
deleteKeyIfNotMounted(key, true);
|
|
202
|
-
}
|
|
203
|
-
if (numToCut > 0 || bytesToCut > 0) {
|
|
204
|
-
if (needUpdate) {
|
|
205
|
-
entriesByTimeAscending = Object.entries(newState).sort(
|
|
206
|
-
(entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
|
|
207
|
-
);
|
|
208
|
-
}
|
|
209
|
-
for (const [key] of entriesByTimeAscending) {
|
|
210
|
-
deleteKeyIfNotMounted(key, false);
|
|
211
|
-
if (numToCut <= 0 && bytesToCut <= 0) {
|
|
212
|
-
break;
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
if (!needUpdate) {
|
|
217
|
-
log(
|
|
218
|
-
`No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
|
|
219
|
-
);
|
|
220
|
-
return;
|
|
221
|
-
}
|
|
222
|
-
queryState.setValue(newState);
|
|
223
|
-
log(
|
|
224
|
-
`Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${_objectsizeof2.default.call(void 0, newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`
|
|
225
|
-
);
|
|
226
|
-
}
|
|
227
|
-
function setData(queryKey, data, dataUpdatedMs = Date.now()) {
|
|
228
|
-
const entry = {
|
|
229
|
-
lastUpdatedMs: Date.now(),
|
|
230
|
-
loading: false,
|
|
231
|
-
data,
|
|
232
|
-
dataUpdatedMs
|
|
233
|
-
};
|
|
234
|
-
queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));
|
|
235
|
-
enforceSizeLimit();
|
|
236
|
-
}
|
|
237
|
-
async function startFetching(queryKey, queryType, args) {
|
|
238
|
-
log(`Start fetching ${queryKey}, queryType=${queryType}`);
|
|
239
|
-
try {
|
|
240
|
-
const data = await (queryType === "refetch" && refetchFn ? refetchFn(...args) : queryFn(...args));
|
|
241
|
-
log(`Successfully fetched ${queryKey}`);
|
|
242
|
-
setData(queryKey, data, Date.now());
|
|
243
|
-
return data;
|
|
244
|
-
} catch (e) {
|
|
245
|
-
log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);
|
|
246
|
-
throw e;
|
|
247
|
-
} finally {
|
|
248
|
-
inflightQueries.delete(queryKey);
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
function dedupedFetch(queryKey, queryType, ...args) {
|
|
252
|
-
const inflightQuery = inflightQueries.get(queryKey);
|
|
253
|
-
if (inflightQuery) {
|
|
254
|
-
log(
|
|
255
|
-
`Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`
|
|
256
|
-
);
|
|
257
|
-
return inflightQuery.promise;
|
|
258
|
-
}
|
|
259
|
-
const promise = startFetching(queryKey, queryType, args);
|
|
260
|
-
const abortController = new AbortController();
|
|
261
|
-
inflightQueries.set(queryKey, { promise, abortController });
|
|
262
|
-
return promise;
|
|
263
|
-
}
|
|
264
|
-
const obj = {
|
|
265
|
-
queryName,
|
|
266
|
-
queryFn,
|
|
267
|
-
refetchFn,
|
|
268
|
-
expiryMs,
|
|
269
|
-
staleMs,
|
|
270
|
-
refetchOnStale,
|
|
271
|
-
maxSize,
|
|
272
|
-
maxBytes,
|
|
273
|
-
keepLastNonEmptyData,
|
|
274
|
-
log,
|
|
275
|
-
queryState,
|
|
276
|
-
/** Returns a key to identify requests based on the given args. */
|
|
277
|
-
getQueryKey(args) {
|
|
278
|
-
let s = _chunk5DO7KC3Lcjs.stringifyDeterministicForKeys.call(void 0, args);
|
|
279
|
-
if (s.length > 30) {
|
|
280
|
-
s = _xxhashjs2.default.h32(s, 39406).toString(16).slice(2);
|
|
281
|
-
}
|
|
282
|
-
return queryName + ":" + s;
|
|
283
|
-
},
|
|
284
|
-
/**
|
|
285
|
-
* Get the AbortController to abort the inflight query (if any).
|
|
286
|
-
*
|
|
287
|
-
* Note that once you get the controller, you can also get the signal easily
|
|
288
|
-
* using `controller.signal`. So if you need both the controller and the
|
|
289
|
-
* signal, just use this function.
|
|
290
|
-
*/
|
|
291
|
-
getAbortController(args) {
|
|
292
|
-
const queryKey = obj.getQueryKey(args);
|
|
293
|
-
return obj.getAbortControllerByKey(queryKey);
|
|
294
|
-
},
|
|
295
|
-
getAbortControllerByKey(queryKey) {
|
|
296
|
-
return _nullishCoalesce(_optionalChain([inflightQueries, 'access', _9 => _9.get, 'call', _10 => _10(queryKey), 'optionalAccess', _11 => _11.abortController]), () => ( null));
|
|
297
|
-
},
|
|
298
|
-
/**
|
|
299
|
-
* Get the AbortSignal to check for query abortions.
|
|
300
|
-
*
|
|
301
|
-
* Example using fetch:
|
|
302
|
-
* ```
|
|
303
|
-
* const getUserQuery = sharedQuery({
|
|
304
|
-
* queryName: "getUser",
|
|
305
|
-
* queryFn: (userId: string) => {
|
|
306
|
-
* // Get the signal for this current execution.
|
|
307
|
-
* const signal = getUserQuery.getAbortSignal([userId]);
|
|
308
|
-
*
|
|
309
|
-
* // Pass the signal to fetch so that it can be aborted.
|
|
310
|
-
* const response = await fetch(`/users/${userId}`, { signal });
|
|
311
|
-
*
|
|
312
|
-
* // Check for errors.
|
|
313
|
-
* if (!response.ok) {
|
|
314
|
-
* throw new Error(response.statusText);
|
|
315
|
-
* }
|
|
316
|
-
*
|
|
317
|
-
* // Return the data.
|
|
318
|
-
* return await response.json();
|
|
319
|
-
* },
|
|
320
|
-
* });
|
|
321
|
-
* ```
|
|
322
|
-
*
|
|
323
|
-
* Example using `fetcher.ts`:
|
|
324
|
-
* ```
|
|
325
|
-
* const getUserQuery = sharedQuery({
|
|
326
|
-
* queryName: "getUser",
|
|
327
|
-
* queryFn: (userId: string) => {
|
|
328
|
-
* // Get the signal for this current execution.
|
|
329
|
-
* const signal = getUserQuery.getAbortSignal([userId]);
|
|
330
|
-
*
|
|
331
|
-
* // Pass the signal to fetch so that it can be aborted.
|
|
332
|
-
* return fetcher.url(`/users/${userId}`).options({ signal }).get().json();
|
|
333
|
-
* },
|
|
334
|
-
* });
|
|
335
|
-
* ```
|
|
336
|
-
*/
|
|
337
|
-
getAbortSignal(args) {
|
|
338
|
-
const queryKey = obj.getQueryKey(args);
|
|
339
|
-
return obj.getAbortSignalByKey(queryKey);
|
|
340
|
-
},
|
|
341
|
-
getAbortSignalByKey(queryKey) {
|
|
342
|
-
return _nullishCoalesce(_optionalChain([obj, 'access', _12 => _12.getAbortControllerByKey, 'call', _13 => _13(queryKey), 'optionalAccess', _14 => _14.signal]), () => ( null));
|
|
343
|
-
},
|
|
344
|
-
/** For cached data, we need to return the correct timestamps as well. */
|
|
345
|
-
async getCachedOrFetch(...args) {
|
|
346
|
-
const startMs = Date.now();
|
|
347
|
-
await queryState.readyPromise;
|
|
348
|
-
const waitedMs = Date.now() - startMs;
|
|
349
|
-
const queryKey = obj.getQueryKey(args);
|
|
350
|
-
const cached = _optionalChain([queryState, 'access', _15 => _15.getSnapshot, 'call', _16 => _16(), 'optionalAccess', _17 => _17[queryKey]]);
|
|
351
|
-
if (waitedMs) {
|
|
352
|
-
log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);
|
|
353
|
-
}
|
|
354
|
-
if (_optionalChain([cached, 'optionalAccess', _18 => _18.data]) && !isExpired(_nullishCoalesce(cached.dataUpdatedMs, () => ( 0)))) {
|
|
355
|
-
if (!isStale(_nullishCoalesce(cached.dataUpdatedMs, () => ( 0)))) {
|
|
356
|
-
log(`Return fresh data ${queryKey} from cache without fetching`);
|
|
357
|
-
return cached;
|
|
358
|
-
}
|
|
359
|
-
if (refetchOnStale) {
|
|
360
|
-
log(`refetchOnStale for ${queryKey}`);
|
|
361
|
-
void dedupedFetch(queryKey, "query", ...args);
|
|
362
|
-
}
|
|
363
|
-
log(`Returning stale data for ${queryKey}`);
|
|
364
|
-
return cached;
|
|
365
|
-
}
|
|
366
|
-
const data = await dedupedFetch(queryKey, "query", ...args);
|
|
367
|
-
const now = Date.now();
|
|
368
|
-
return {
|
|
369
|
-
// Don't keep old error.
|
|
370
|
-
lastUpdatedMs: now,
|
|
371
|
-
loading: false,
|
|
372
|
-
data,
|
|
373
|
-
dataUpdatedMs: now
|
|
374
|
-
};
|
|
375
|
-
},
|
|
376
|
-
/** Get the entire stored entry for a query key. */
|
|
377
|
-
getQueryValue(queryKey) {
|
|
378
|
-
return _optionalChain([queryState, 'access', _19 => _19.getSnapshot, 'call', _20 => _20(), 'optionalAccess', _21 => _21[queryKey]]);
|
|
379
|
-
},
|
|
380
|
-
/** Get the current stored data for a query key. */
|
|
381
|
-
getData(queryKey) {
|
|
382
|
-
const stateValue = _optionalChain([queryState, 'access', _22 => _22.getSnapshot, 'call', _23 => _23(), 'optionalAccess', _24 => _24[queryKey]]);
|
|
383
|
-
if (_optionalChain([stateValue, 'optionalAccess', _25 => _25.lastUpdatedMs])) {
|
|
384
|
-
if (isExpired(stateValue.lastUpdatedMs)) {
|
|
385
|
-
obj.deleteData(queryKey);
|
|
386
|
-
return void 0;
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
return _optionalChain([stateValue, 'optionalAccess', _26 => _26.data]);
|
|
390
|
-
},
|
|
391
|
-
/** Set the data directly if the user obtained it from somewhere else. */
|
|
392
|
-
setData,
|
|
393
|
-
/**
|
|
394
|
-
* Do a new fetch even when the data is already cached, but don't fetch if
|
|
395
|
-
* another fetch is already inflight.
|
|
396
|
-
*/
|
|
397
|
-
async updateFromSource(...args) {
|
|
398
|
-
const key = obj.getQueryKey(args);
|
|
399
|
-
return await dedupedFetch(key, "query", ...args);
|
|
400
|
-
},
|
|
401
|
-
/**
|
|
402
|
-
* Perform an explicit refetch. If `options.refetchFn` was not specified,
|
|
403
|
-
* then this would be identical to calling `obj.updateFromSource()`.
|
|
404
|
-
*/
|
|
405
|
-
async refetch(...args) {
|
|
406
|
-
const key = obj.getQueryKey(args);
|
|
407
|
-
return await dedupedFetch(key, "refetch", ...args);
|
|
408
|
-
},
|
|
409
|
-
/** Delete the cached data for one set of arguments. */
|
|
410
|
-
deleteData(queryKey) {
|
|
411
|
-
const record = queryState.getSnapshot();
|
|
412
|
-
const clone = { ...record };
|
|
413
|
-
delete clone[queryKey];
|
|
414
|
-
queryState.setValue(clone);
|
|
415
|
-
const inflight = inflightQueries.get(queryKey);
|
|
416
|
-
if (inflight) {
|
|
417
|
-
inflightQueries.delete(queryKey);
|
|
418
|
-
inflight.abortController.abort("Deleted");
|
|
419
|
-
}
|
|
420
|
-
},
|
|
421
|
-
/** Delete all currently cached data & all inflight promises. */
|
|
422
|
-
clear() {
|
|
423
|
-
queryState.delete();
|
|
424
|
-
for (const { abortController } of Array.from(inflightQueries.values())) {
|
|
425
|
-
abortController.abort("Cleared");
|
|
426
|
-
}
|
|
427
|
-
inflightQueries.clear();
|
|
428
|
-
},
|
|
429
|
-
/** Keep track of mounted keys. */
|
|
430
|
-
mount(queryKey) {
|
|
431
|
-
mountedKeys.set(queryKey, (_nullishCoalesce(mountedKeys.get(queryKey), () => ( 0))) + 1);
|
|
432
|
-
},
|
|
433
|
-
/** Clean up mounted keys. */
|
|
434
|
-
unmount(queryKey) {
|
|
435
|
-
const count = mountedKeys.get(queryKey);
|
|
436
|
-
if (count === 1) {
|
|
437
|
-
mountedKeys.delete(queryKey);
|
|
438
|
-
} else {
|
|
439
|
-
mountedKeys.set(queryKey, (_nullishCoalesce(count, () => ( 0))) - 1);
|
|
440
|
-
}
|
|
441
|
-
},
|
|
442
|
-
/**
|
|
443
|
-
* Discard the oldest entries if the size exceeds the limit. The last
|
|
444
|
-
* remaining record cannot be deleted no matter what the limit is.
|
|
445
|
-
*/
|
|
446
|
-
enforceSizeLimit
|
|
447
|
-
};
|
|
448
|
-
return obj;
|
|
449
|
-
}
|
|
450
|
-
var DEFAULT_QUERY_STATE_ENTRY = {
|
|
451
|
-
lastUpdatedMs: 0,
|
|
452
|
-
loading: true
|
|
453
|
-
};
|
|
454
|
-
function useSharedQuery(query, ...args) {
|
|
455
|
-
const stableArgs = _chunkWVLPJPWGcjs.useDeepMemo.call(void 0, args);
|
|
456
|
-
const [queryState, setQueryState] = _chunk3X25NN6Xcjs.useSharedState.call(void 0, query.queryState);
|
|
457
|
-
const isMounted = _react.useRef.call(void 0, true);
|
|
458
|
-
const queryKey = _react.useMemo.call(void 0,
|
|
459
|
-
() => query.getQueryKey(stableArgs),
|
|
460
|
-
[query, stableArgs]
|
|
461
|
-
);
|
|
462
|
-
const queryStateValue = _nullishCoalesce(queryState[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY));
|
|
463
|
-
const setQueryStateValue = _react.useCallback.call(void 0,
|
|
464
|
-
(next) => {
|
|
465
|
-
setQueryState((prev) => {
|
|
466
|
-
const clone = { ...prev };
|
|
467
|
-
clone[queryKey] = typeof next === "function" ? next(_nullishCoalesce(clone[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY))) : next;
|
|
468
|
-
return clone;
|
|
469
|
-
});
|
|
470
|
-
},
|
|
471
|
-
[queryKey, setQueryState]
|
|
472
|
-
);
|
|
473
|
-
const [lastNonEmptyData, setLastNonEmptyData] = _react.useState.call(void 0, );
|
|
474
|
-
_react.useEffect.call(void 0, () => {
|
|
475
|
-
if (query.keepLastNonEmptyData && queryStateValue.data !== void 0) {
|
|
476
|
-
setLastNonEmptyData(queryStateValue.data);
|
|
477
|
-
}
|
|
478
|
-
}, [query.keepLastNonEmptyData, queryStateValue.data]);
|
|
479
|
-
const execute = _react.useCallback.call(void 0,
|
|
480
|
-
async (isRefetch) => {
|
|
481
|
-
query.log(
|
|
482
|
-
`Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`
|
|
483
|
-
);
|
|
484
|
-
if (!isMounted.current) return;
|
|
485
|
-
setQueryStateValue((prev) => ({
|
|
486
|
-
// Keep old data and error.
|
|
487
|
-
...prev,
|
|
488
|
-
lastUpdatedMs: Date.now(),
|
|
489
|
-
loading: true
|
|
490
|
-
}));
|
|
491
|
-
try {
|
|
492
|
-
let state;
|
|
493
|
-
if (isRefetch) {
|
|
494
|
-
const data = await query.refetch(...stableArgs);
|
|
495
|
-
const now = Date.now();
|
|
496
|
-
state = {
|
|
497
|
-
// Don't keep old error.
|
|
498
|
-
lastUpdatedMs: now,
|
|
499
|
-
loading: false,
|
|
500
|
-
data,
|
|
501
|
-
dataUpdatedMs: now
|
|
502
|
-
};
|
|
503
|
-
} else {
|
|
504
|
-
state = await query.getCachedOrFetch(...stableArgs);
|
|
505
|
-
}
|
|
506
|
-
if (!isMounted.current) return;
|
|
507
|
-
setQueryStateValue({ ...state, loading: false });
|
|
508
|
-
} catch (e) {
|
|
509
|
-
if (!isMounted.current) return;
|
|
510
|
-
const now = Date.now();
|
|
511
|
-
setQueryStateValue((prev) => ({
|
|
512
|
-
// Keep old data.
|
|
513
|
-
...prev,
|
|
514
|
-
lastUpdatedMs: now,
|
|
515
|
-
loading: false,
|
|
516
|
-
error: e,
|
|
517
|
-
errorUpdatedMs: now
|
|
518
|
-
}));
|
|
519
|
-
}
|
|
520
|
-
},
|
|
521
|
-
[query, queryKey, setQueryStateValue, stableArgs]
|
|
522
|
-
);
|
|
523
|
-
_react.useEffect.call(void 0, () => {
|
|
524
|
-
isMounted.current = true;
|
|
525
|
-
query.mount(queryKey);
|
|
526
|
-
void execute(false);
|
|
527
|
-
return () => {
|
|
528
|
-
isMounted.current = false;
|
|
529
|
-
query.unmount(queryKey);
|
|
530
|
-
};
|
|
531
|
-
}, [execute, query, queryKey]);
|
|
532
|
-
return _react.useMemo.call(void 0, () => {
|
|
533
|
-
return {
|
|
534
|
-
...queryStateValue,
|
|
535
|
-
// Fill with lastNonEmptyData when data is undefined.
|
|
536
|
-
data: queryStateValue.data !== void 0 ? queryStateValue.data : lastNonEmptyData,
|
|
537
|
-
latestData: queryStateValue.data,
|
|
538
|
-
// This works only if the user-given queryFn supports abort. If not,
|
|
539
|
-
// this function doesn't do anything, since we don't have any means to
|
|
540
|
-
// abort the running queryFn.
|
|
541
|
-
abortCurrentQuery: (reason) => {
|
|
542
|
-
const controller = query.getAbortControllerByKey(queryKey);
|
|
543
|
-
_optionalChain([controller, 'optionalAccess', _27 => _27.abort, 'call', _28 => _28(reason)]);
|
|
544
|
-
return Boolean(controller);
|
|
545
|
-
},
|
|
546
|
-
refetch: () => {
|
|
547
|
-
return execute(true);
|
|
548
|
-
},
|
|
549
|
-
setData: (data, dataUpdatedMs) => {
|
|
550
|
-
query.setData(queryKey, data, dataUpdatedMs);
|
|
551
|
-
},
|
|
552
|
-
deleteData: () => {
|
|
553
|
-
query.deleteData(queryKey);
|
|
554
|
-
}
|
|
555
|
-
};
|
|
556
|
-
}, [execute, lastNonEmptyData, query, queryKey, queryStateValue]);
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
exports.SharedQueryConfig = SharedQueryConfig; exports.configureSharedQuery = configureSharedQuery; exports.sharedQuery = sharedQuery; exports.useSharedQuery = useSharedQuery;
|
|
17
|
+
exports.SharedQueryConfig = _chunkGKNOICX3cjs.SharedQueryConfig; exports.configureSharedQuery = _chunkGKNOICX3cjs.configureSharedQuery; exports.sharedQuery = _chunkGKNOICX3cjs.sharedQuery; exports.useSharedQuery = _chunkGKNOICX3cjs.useSharedQuery;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { SetStateAction } from 'react';
|
|
2
|
-
import { SharedStateOptions } from './sharedState.
|
|
3
|
-
import { PersistTo } from './storage.
|
|
2
|
+
import { SharedStateOptions } from './sharedState.cjs';
|
|
3
|
+
import { PersistTo } from './storage.cjs';
|
|
4
4
|
import '@choksheak/ts-utils/duration';
|
|
5
5
|
import '@choksheak/ts-utils/storageAdapter';
|
|
6
6
|
|
|
@@ -323,7 +323,7 @@ declare function sharedQuery<TArgs extends unknown[], TData>(options: SharedQuer
|
|
|
323
323
|
* });
|
|
324
324
|
* ```
|
|
325
325
|
*
|
|
326
|
-
* Example using `
|
|
326
|
+
* Example using `http.ts`:
|
|
327
327
|
* ```
|
|
328
328
|
* const getUserQuery = sharedQuery({
|
|
329
329
|
* queryName: "getUser",
|
|
@@ -332,7 +332,8 @@ declare function sharedQuery<TArgs extends unknown[], TData>(options: SharedQuer
|
|
|
332
332
|
* const signal = getUserQuery.getAbortSignal([userId]);
|
|
333
333
|
*
|
|
334
334
|
* // Pass the signal to fetch so that it can be aborted.
|
|
335
|
-
*
|
|
335
|
+
* const response = await http.get(`/users/${userId}`, { signal });
|
|
336
|
+
* return await response.json();
|
|
336
337
|
* },
|
|
337
338
|
* });
|
|
338
339
|
* ```
|