@khanacademy/wonder-blocks-data 6.0.0 → 7.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/es/index.js +64 -689
- package/dist/index.js +38 -49
- package/legacy-docs.md +1 -1
- package/package.json +3 -3
- package/src/__docs__/exports.use-server-effect.stories.mdx +13 -1
- package/src/hooks/__tests__/use-hydratable-effect.test.js +22 -25
- package/src/hooks/__tests__/use-server-effect.test.js +51 -0
- package/src/hooks/use-hydratable-effect.js +13 -13
- package/src/hooks/use-server-effect.js +30 -5
- package/src/util/abort-error.js +0 -15
package/dist/es/index.js
CHANGED
|
@@ -4,47 +4,14 @@ import _extends from '@babel/runtime/helpers/extends';
|
|
|
4
4
|
import * as React from 'react';
|
|
5
5
|
import { useContext, useRef, useMemo, useCallback } from 'react';
|
|
6
6
|
|
|
7
|
-
/**
|
|
8
|
-
* Error kinds for DataError.
|
|
9
|
-
*/
|
|
10
7
|
const DataErrors = Object.freeze({
|
|
11
|
-
/**
|
|
12
|
-
* The kind of error is not known.
|
|
13
|
-
*/
|
|
14
8
|
Unknown: "Unknown",
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* The error is internal to the executing code.
|
|
18
|
-
*/
|
|
19
9
|
Internal: "Internal",
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* There was a problem with the provided input.
|
|
23
|
-
*/
|
|
24
10
|
InvalidInput: "InvalidInput",
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* A network error occurred.
|
|
28
|
-
*/
|
|
29
11
|
Network: "Network",
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Response could not be parsed.
|
|
33
|
-
*/
|
|
34
12
|
Parse: "Parse",
|
|
35
|
-
|
|
36
|
-
/**
|
|
37
|
-
* An error that occurred during SSR and was hydrated from cache
|
|
38
|
-
*/
|
|
39
13
|
Hydrated: "Hydrated"
|
|
40
14
|
});
|
|
41
|
-
/**
|
|
42
|
-
* An error from the Wonder Blocks Data API.
|
|
43
|
-
*
|
|
44
|
-
* Errors of this type will have names of the format:
|
|
45
|
-
* `${kind}DataError`
|
|
46
|
-
*/
|
|
47
|
-
|
|
48
15
|
class DataError extends KindError {
|
|
49
16
|
constructor(message, kind, {
|
|
50
17
|
metadata,
|
|
@@ -59,27 +26,14 @@ class DataError extends KindError {
|
|
|
59
26
|
|
|
60
27
|
}
|
|
61
28
|
|
|
62
|
-
/**
|
|
63
|
-
* Describe an in-memory cache.
|
|
64
|
-
*/
|
|
65
29
|
class ScopedInMemoryCache {
|
|
66
30
|
constructor(initialCache = {}) {
|
|
67
31
|
this._cache = initialCache;
|
|
68
32
|
}
|
|
69
|
-
/**
|
|
70
|
-
* Indicate if this cache is being used or not.
|
|
71
|
-
*
|
|
72
|
-
* When the cache has entries, returns `true`; otherwise, returns `false`.
|
|
73
|
-
*/
|
|
74
|
-
|
|
75
33
|
|
|
76
34
|
get inUse() {
|
|
77
35
|
return Object.keys(this._cache).length > 0;
|
|
78
36
|
}
|
|
79
|
-
/**
|
|
80
|
-
* Set a value in the cache.
|
|
81
|
-
*/
|
|
82
|
-
|
|
83
37
|
|
|
84
38
|
set(scope, id, value) {
|
|
85
39
|
var _this$_cache$scope;
|
|
@@ -99,20 +53,12 @@ class ScopedInMemoryCache {
|
|
|
99
53
|
this._cache[scope] = (_this$_cache$scope = this._cache[scope]) != null ? _this$_cache$scope : {};
|
|
100
54
|
this._cache[scope][id] = value;
|
|
101
55
|
}
|
|
102
|
-
/**
|
|
103
|
-
* Retrieve a value from the cache.
|
|
104
|
-
*/
|
|
105
|
-
|
|
106
56
|
|
|
107
57
|
get(scope, id) {
|
|
108
58
|
var _this$_cache$scope$id, _this$_cache$scope2;
|
|
109
59
|
|
|
110
60
|
return (_this$_cache$scope$id = (_this$_cache$scope2 = this._cache[scope]) == null ? void 0 : _this$_cache$scope2[id]) != null ? _this$_cache$scope$id : null;
|
|
111
61
|
}
|
|
112
|
-
/**
|
|
113
|
-
* Purge an item from the cache.
|
|
114
|
-
*/
|
|
115
|
-
|
|
116
62
|
|
|
117
63
|
purge(scope, id) {
|
|
118
64
|
var _this$_cache$scope3;
|
|
@@ -127,12 +73,6 @@ class ScopedInMemoryCache {
|
|
|
127
73
|
delete this._cache[scope];
|
|
128
74
|
}
|
|
129
75
|
}
|
|
130
|
-
/**
|
|
131
|
-
* Purge a scope of items that match the given predicate.
|
|
132
|
-
*
|
|
133
|
-
* If the predicate is omitted, then all items in the scope are purged.
|
|
134
|
-
*/
|
|
135
|
-
|
|
136
76
|
|
|
137
77
|
purgeScope(scope, predicate) {
|
|
138
78
|
if (!this._cache[scope]) {
|
|
@@ -154,12 +94,6 @@ class ScopedInMemoryCache {
|
|
|
154
94
|
delete this._cache[scope];
|
|
155
95
|
}
|
|
156
96
|
}
|
|
157
|
-
/**
|
|
158
|
-
* Purge all items from the cache that match the given predicate.
|
|
159
|
-
*
|
|
160
|
-
* If the predicate is omitted, then all items in the cache are purged.
|
|
161
|
-
*/
|
|
162
|
-
|
|
163
97
|
|
|
164
98
|
purgeAll(predicate) {
|
|
165
99
|
if (predicate == null) {
|
|
@@ -174,9 +108,6 @@ class ScopedInMemoryCache {
|
|
|
174
108
|
|
|
175
109
|
}
|
|
176
110
|
|
|
177
|
-
/**
|
|
178
|
-
* Describe a serializable in-memory cache.
|
|
179
|
-
*/
|
|
180
111
|
class SerializableInMemoryCache extends ScopedInMemoryCache {
|
|
181
112
|
constructor(initialCache = {}) {
|
|
182
113
|
try {
|
|
@@ -185,18 +116,10 @@ class SerializableInMemoryCache extends ScopedInMemoryCache {
|
|
|
185
116
|
throw new DataError(`An error occurred trying to initialize from a response cache snapshot: ${e}`, DataErrors.InvalidInput);
|
|
186
117
|
}
|
|
187
118
|
}
|
|
188
|
-
/**
|
|
189
|
-
* Set a value in the cache.
|
|
190
|
-
*/
|
|
191
|
-
|
|
192
119
|
|
|
193
120
|
set(scope, id, value) {
|
|
194
121
|
super.set(scope, id, Object.freeze(clone(value)));
|
|
195
122
|
}
|
|
196
|
-
/**
|
|
197
|
-
* Clone the cache.
|
|
198
|
-
*/
|
|
199
|
-
|
|
200
123
|
|
|
201
124
|
clone() {
|
|
202
125
|
try {
|
|
@@ -211,18 +134,8 @@ class SerializableInMemoryCache extends ScopedInMemoryCache {
|
|
|
211
134
|
}
|
|
212
135
|
|
|
213
136
|
const DefaultScope$2 = "default";
|
|
214
|
-
/**
|
|
215
|
-
* The default instance is stored here.
|
|
216
|
-
* It's created below in the Default() static property.
|
|
217
|
-
*/
|
|
218
137
|
|
|
219
138
|
let _default$2;
|
|
220
|
-
/**
|
|
221
|
-
* Implements the response cache.
|
|
222
|
-
*
|
|
223
|
-
* INTERNAL USE ONLY
|
|
224
|
-
*/
|
|
225
|
-
|
|
226
139
|
|
|
227
140
|
class SsrCache {
|
|
228
141
|
static get Default() {
|
|
@@ -240,7 +153,6 @@ class SsrCache {
|
|
|
240
153
|
}
|
|
241
154
|
|
|
242
155
|
this._hydrationCache = new SerializableInMemoryCache({
|
|
243
|
-
// $FlowIgnore[incompatible-call]
|
|
244
156
|
[DefaultScope$2]: source
|
|
245
157
|
});
|
|
246
158
|
};
|
|
@@ -259,23 +171,11 @@ class SsrCache {
|
|
|
259
171
|
this.getEntry = id => {
|
|
260
172
|
var _this$_ssrOnlyCache$g, _this$_ssrOnlyCache;
|
|
261
173
|
|
|
262
|
-
|
|
263
|
-
// We first look in the ssr cache and then the hydration cache.
|
|
264
|
-
const internalEntry = (_this$_ssrOnlyCache$g = (_this$_ssrOnlyCache = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache.get(DefaultScope$2, id)) != null ? _this$_ssrOnlyCache$g : this._hydrationCache.get(DefaultScope$2, id); // If we are not server-side and we hydrated something, let's clear
|
|
265
|
-
// that from the hydration cache to save memory.
|
|
174
|
+
const internalEntry = (_this$_ssrOnlyCache$g = (_this$_ssrOnlyCache = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache.get(DefaultScope$2, id)) != null ? _this$_ssrOnlyCache$g : this._hydrationCache.get(DefaultScope$2, id);
|
|
266
175
|
|
|
267
176
|
if (this._ssrOnlyCache == null && internalEntry != null) {
|
|
268
|
-
// We now delete this from our hydration cache as we don't need it.
|
|
269
|
-
// This does mean that if another handler of the same type but
|
|
270
|
-
// without some sort of linked cache won't get the value, but
|
|
271
|
-
// that's not an expected use-case. If two different places use the
|
|
272
|
-
// same handler and options (i.e. the same request), then the
|
|
273
|
-
// handler should cater to that to ensure they share the result.
|
|
274
177
|
this._hydrationCache.purge(DefaultScope$2, id);
|
|
275
|
-
}
|
|
276
|
-
// is hard. Just telling flow it's OK.
|
|
277
|
-
// $FlowIgnore[incompatible-return]
|
|
278
|
-
|
|
178
|
+
}
|
|
279
179
|
|
|
280
180
|
return internalEntry;
|
|
281
181
|
};
|
|
@@ -283,20 +183,13 @@ class SsrCache {
|
|
|
283
183
|
this.remove = id => {
|
|
284
184
|
var _this$_ssrOnlyCache$p, _this$_ssrOnlyCache2;
|
|
285
185
|
|
|
286
|
-
// NOTE(somewhatabstract): We could invoke removeAll with a predicate
|
|
287
|
-
// to match the key of the entry we're removing, but that's an
|
|
288
|
-
// inefficient way to remove a single item, so let's not do that.
|
|
289
|
-
// Delete the entry from the appropriate cache.
|
|
290
186
|
return this._hydrationCache.purge(DefaultScope$2, id) || ((_this$_ssrOnlyCache$p = (_this$_ssrOnlyCache2 = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache2.purge(DefaultScope$2, id)) != null ? _this$_ssrOnlyCache$p : false);
|
|
291
187
|
};
|
|
292
188
|
|
|
293
189
|
this.removeAll = predicate => {
|
|
294
190
|
var _this$_ssrOnlyCache3;
|
|
295
191
|
|
|
296
|
-
const realPredicate = predicate ?
|
|
297
|
-
// conforms.
|
|
298
|
-
// $FlowIgnore[incompatible-call]
|
|
299
|
-
(_, key, cachedEntry) => predicate(key, cachedEntry) : undefined; // Apply the predicate to what we have in our caches.
|
|
192
|
+
const realPredicate = predicate ? (_, key, cachedEntry) => predicate(key, cachedEntry) : undefined;
|
|
300
193
|
|
|
301
194
|
this._hydrationCache.purgeAll(realPredicate);
|
|
302
195
|
|
|
@@ -306,13 +199,7 @@ class SsrCache {
|
|
|
306
199
|
this.cloneHydratableData = () => {
|
|
307
200
|
var _cache$DefaultScope;
|
|
308
201
|
|
|
309
|
-
|
|
310
|
-
const cache = this._hydrationCache.clone(); // If we're empty, we still want to return an object, so we default
|
|
311
|
-
// to an empty object.
|
|
312
|
-
// We only need the default scope out of our scoped in-memory cache.
|
|
313
|
-
// We know that it conforms to our expectations.
|
|
314
|
-
// $FlowIgnore[incompatible-return]
|
|
315
|
-
|
|
202
|
+
const cache = this._hydrationCache.clone();
|
|
316
203
|
|
|
317
204
|
return (_cache$DefaultScope = cache[DefaultScope$2]) != null ? _cache$DefaultScope : {};
|
|
318
205
|
};
|
|
@@ -325,36 +212,21 @@ class SsrCache {
|
|
|
325
212
|
const frozenEntry = Object.freeze(entry);
|
|
326
213
|
|
|
327
214
|
if (Server.isServerSide()) {
|
|
328
|
-
// We are server-side.
|
|
329
|
-
// We need to store this value.
|
|
330
215
|
if (hydrate) {
|
|
331
216
|
this._hydrationCache.set(DefaultScope$2, id, frozenEntry);
|
|
332
217
|
} else {
|
|
333
218
|
var _this$_ssrOnlyCache4;
|
|
334
219
|
|
|
335
|
-
// Usually, when server-side, this cache will always be present.
|
|
336
|
-
// We do fake server-side in our doc example though, when it
|
|
337
|
-
// won't be.
|
|
338
220
|
(_this$_ssrOnlyCache4 = this._ssrOnlyCache) == null ? void 0 : _this$_ssrOnlyCache4.set(DefaultScope$2, id, frozenEntry);
|
|
339
221
|
}
|
|
340
222
|
}
|
|
341
223
|
|
|
342
224
|
return frozenEntry;
|
|
343
225
|
}
|
|
344
|
-
/**
|
|
345
|
-
* Initialize the cache from a given cache state.
|
|
346
|
-
*
|
|
347
|
-
* This can only be called if the cache is not already in use.
|
|
348
|
-
*/
|
|
349
|
-
|
|
350
226
|
|
|
351
227
|
}
|
|
352
228
|
|
|
353
229
|
let _default$1;
|
|
354
|
-
/**
|
|
355
|
-
* This fulfills a request, making sure that in-flight requests are shared.
|
|
356
|
-
*/
|
|
357
|
-
|
|
358
230
|
|
|
359
231
|
class RequestFulfillment {
|
|
360
232
|
constructor() {
|
|
@@ -364,18 +236,11 @@ class RequestFulfillment {
|
|
|
364
236
|
handler,
|
|
365
237
|
hydrate: _hydrate = true
|
|
366
238
|
}) => {
|
|
367
|
-
/**
|
|
368
|
-
* If we have an inflight request, we'll provide that.
|
|
369
|
-
*/
|
|
370
239
|
const inflight = this._requests[id];
|
|
371
240
|
|
|
372
241
|
if (inflight) {
|
|
373
242
|
return inflight;
|
|
374
243
|
}
|
|
375
|
-
/**
|
|
376
|
-
* We don't have an inflight request, so let's set one up.
|
|
377
|
-
*/
|
|
378
|
-
|
|
379
244
|
|
|
380
245
|
const request = handler().then(data => ({
|
|
381
246
|
status: "success",
|
|
@@ -385,13 +250,7 @@ class RequestFulfillment {
|
|
|
385
250
|
metadata: {
|
|
386
251
|
unexpectedError: error
|
|
387
252
|
}
|
|
388
|
-
}) : error;
|
|
389
|
-
// The only way to detect this reliably, it seems, is to
|
|
390
|
-
// check the error name and see if it's "AbortError" (this
|
|
391
|
-
// is also what Apollo does).
|
|
392
|
-
// Even then, it's reliant on the handler supporting aborts.
|
|
393
|
-
// TODO(somewhatabstract, FEI-4276): Add first class abort
|
|
394
|
-
// support to the handler API.
|
|
253
|
+
}) : error;
|
|
395
254
|
|
|
396
255
|
if (actualError.name === "AbortError") {
|
|
397
256
|
return {
|
|
@@ -405,8 +264,7 @@ class RequestFulfillment {
|
|
|
405
264
|
};
|
|
406
265
|
}).finally(() => {
|
|
407
266
|
delete this._requests[id];
|
|
408
|
-
});
|
|
409
|
-
|
|
267
|
+
});
|
|
410
268
|
this._requests[id] = request;
|
|
411
269
|
return request;
|
|
412
270
|
};
|
|
@@ -422,24 +280,9 @@ class RequestFulfillment {
|
|
|
422
280
|
|
|
423
281
|
}
|
|
424
282
|
|
|
425
|
-
/**
|
|
426
|
-
* Used to inject our tracking function into the render framework.
|
|
427
|
-
*
|
|
428
|
-
* INTERNAL USE ONLY
|
|
429
|
-
*/
|
|
430
283
|
const TrackerContext = new React.createContext(null);
|
|
431
|
-
/**
|
|
432
|
-
* The default instance is stored here.
|
|
433
|
-
* It's created below in the Default() static property.
|
|
434
|
-
*/
|
|
435
284
|
|
|
436
285
|
let _default;
|
|
437
|
-
/**
|
|
438
|
-
* Implements request tracking and fulfillment.
|
|
439
|
-
*
|
|
440
|
-
* INTERNAL USE ONLY
|
|
441
|
-
*/
|
|
442
|
-
|
|
443
286
|
|
|
444
287
|
class RequestTracker {
|
|
445
288
|
static get Default() {
|
|
@@ -449,18 +292,11 @@ class RequestTracker {
|
|
|
449
292
|
|
|
450
293
|
return _default;
|
|
451
294
|
}
|
|
452
|
-
/**
|
|
453
|
-
* These are the caches for tracked requests, their handlers, and responses.
|
|
454
|
-
*/
|
|
455
|
-
|
|
456
295
|
|
|
457
296
|
constructor(responseCache = undefined) {
|
|
458
297
|
this._trackedRequests = {};
|
|
459
298
|
|
|
460
299
|
this.trackDataRequest = (id, handler, hydrate) => {
|
|
461
|
-
/**
|
|
462
|
-
* If we don't already have this tracked, then let's track it.
|
|
463
|
-
*/
|
|
464
300
|
if (this._trackedRequests[id] == null) {
|
|
465
301
|
this._trackedRequests[id] = {
|
|
466
302
|
handler,
|
|
@@ -487,144 +323,54 @@ class RequestTracker {
|
|
|
487
323
|
promises.push(this._requestFulfillment.fulfill(requestKey, _extends({}, options)).then(result => {
|
|
488
324
|
switch (result.status) {
|
|
489
325
|
case "success":
|
|
490
|
-
/**
|
|
491
|
-
* Let's cache the data!
|
|
492
|
-
*
|
|
493
|
-
* NOTE: This only caches when we're
|
|
494
|
-
* server side.
|
|
495
|
-
*/
|
|
496
326
|
cacheData(requestKey, result.data, options.hydrate);
|
|
497
327
|
break;
|
|
498
328
|
|
|
499
329
|
case "error":
|
|
500
|
-
/**
|
|
501
|
-
* Let's cache the error!
|
|
502
|
-
*
|
|
503
|
-
* NOTE: This only caches when we're
|
|
504
|
-
* server side.
|
|
505
|
-
*/
|
|
506
330
|
cacheError(requestKey, result.error, options.hydrate);
|
|
507
331
|
break;
|
|
508
|
-
}
|
|
509
|
-
// Could never get here unless we wrote
|
|
510
|
-
// the code wrong. Rather than bloat
|
|
511
|
-
// code with useless error, just ignore.
|
|
512
|
-
// For status === "aborted":
|
|
513
|
-
// We won't cache this.
|
|
514
|
-
// We don't hydrate aborted requests,
|
|
515
|
-
// so the client would just see them
|
|
516
|
-
// as unfulfilled data.
|
|
517
|
-
|
|
332
|
+
}
|
|
518
333
|
|
|
519
334
|
return;
|
|
520
335
|
}));
|
|
521
336
|
} catch (e) {
|
|
522
|
-
// This captures if there are problems in the code that
|
|
523
|
-
// begins the requests.
|
|
524
337
|
promises.push(Promise.resolve(cacheError(requestKey, e, options.hydrate)));
|
|
525
338
|
}
|
|
526
339
|
}
|
|
527
|
-
/**
|
|
528
|
-
* Clear out our tracked info.
|
|
529
|
-
*
|
|
530
|
-
* We call this now for a simpler API.
|
|
531
|
-
*
|
|
532
|
-
* If we reset the tracked calls after all promises resolve, any
|
|
533
|
-
* request tracking done while promises are in flight would be lost.
|
|
534
|
-
*
|
|
535
|
-
* If we don't reset at all, then we have to expose the `reset` call
|
|
536
|
-
* for consumers to use, or they'll only ever be able to accumulate
|
|
537
|
-
* more and more tracked requests, having to fulfill them all every
|
|
538
|
-
* time.
|
|
539
|
-
*
|
|
540
|
-
* Calling it here means we can have multiple "track -> request"
|
|
541
|
-
* cycles in a row and in an easy to reason about manner.
|
|
542
|
-
*/
|
|
543
|
-
|
|
544
340
|
|
|
545
341
|
this.reset();
|
|
546
|
-
/**
|
|
547
|
-
* Let's wait for everything to fulfill, and then clone the cached data.
|
|
548
|
-
*/
|
|
549
|
-
|
|
550
342
|
return Promise.all(promises).then(() => this._responseCache.cloneHydratableData());
|
|
551
343
|
};
|
|
552
344
|
|
|
553
345
|
this._responseCache = responseCache || SsrCache.Default;
|
|
554
346
|
this._requestFulfillment = new RequestFulfillment();
|
|
555
347
|
}
|
|
556
|
-
/**
|
|
557
|
-
* Track a request.
|
|
558
|
-
*
|
|
559
|
-
* This method caches a request and its handler for use during server-side
|
|
560
|
-
* rendering to allow us to fulfill requests before producing a final render.
|
|
561
|
-
*/
|
|
562
348
|
|
|
563
|
-
|
|
564
|
-
/**
|
|
565
|
-
* Indicates if we have requests waiting to be fulfilled.
|
|
566
|
-
*/
|
|
567
349
|
get hasUnfulfilledRequests() {
|
|
568
350
|
return Object.keys(this._trackedRequests).length > 0;
|
|
569
351
|
}
|
|
570
|
-
/**
|
|
571
|
-
* Initiate fulfillment of all tracked requests.
|
|
572
|
-
*
|
|
573
|
-
* This loops over the requests that were tracked using TrackData, and asks
|
|
574
|
-
* the respective handlers to fulfill those requests in the order they were
|
|
575
|
-
* tracked.
|
|
576
|
-
*
|
|
577
|
-
* Calling this method marks tracked requests as fulfilled; requests are
|
|
578
|
-
* removed from the list of tracked requests by calling this method.
|
|
579
|
-
*
|
|
580
|
-
* @returns {Promise<ResponseCache>} The promise of the data that was
|
|
581
|
-
* cached as a result of fulfilling the tracked requests.
|
|
582
|
-
*/
|
|
583
|
-
|
|
584
352
|
|
|
585
353
|
}
|
|
586
354
|
|
|
587
|
-
/**
|
|
588
|
-
* Component to enable data request tracking when server-side rendering.
|
|
589
|
-
*/
|
|
590
355
|
class TrackData extends React.Component {
|
|
591
356
|
render() {
|
|
592
357
|
if (!Server.isServerSide()) {
|
|
593
358
|
throw new Error("This component is not for use during client-side rendering");
|
|
594
359
|
}
|
|
595
360
|
|
|
596
|
-
return
|
|
361
|
+
return React.createElement(TrackerContext.Provider, {
|
|
597
362
|
value: RequestTracker.Default.trackDataRequest
|
|
598
363
|
}, this.props.children);
|
|
599
364
|
}
|
|
600
365
|
|
|
601
366
|
}
|
|
602
367
|
|
|
603
|
-
/**
|
|
604
|
-
* Simple implementation to represent aborting.
|
|
605
|
-
*
|
|
606
|
-
* Other frameworks may provide this too, so we won't be sharing this with
|
|
607
|
-
* the outside world. It's just a utility for test and internal use whenever
|
|
608
|
-
* we need to represent the concept of aborted things.
|
|
609
|
-
*/
|
|
610
|
-
class AbortError extends Error {
|
|
611
|
-
constructor(message) {
|
|
612
|
-
super(message);
|
|
613
|
-
this.name = "AbortError";
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
}
|
|
617
|
-
|
|
618
368
|
const loadingStatus = Object.freeze({
|
|
619
369
|
status: "loading"
|
|
620
370
|
});
|
|
621
371
|
const abortedStatus = Object.freeze({
|
|
622
372
|
status: "aborted"
|
|
623
373
|
});
|
|
624
|
-
/**
|
|
625
|
-
* Create Result<TData> instances with specific statuses.
|
|
626
|
-
*/
|
|
627
|
-
|
|
628
374
|
const Status = Object.freeze({
|
|
629
375
|
loading: () => loadingStatus,
|
|
630
376
|
aborted: () => abortedStatus,
|
|
@@ -638,11 +384,7 @@ const Status = Object.freeze({
|
|
|
638
384
|
})
|
|
639
385
|
});
|
|
640
386
|
|
|
641
|
-
/**
|
|
642
|
-
* Turns a cache entry into a stateful result.
|
|
643
|
-
*/
|
|
644
387
|
const resultFromCachedResponse = cacheEntry => {
|
|
645
|
-
// No cache entry means no result to be hydrated.
|
|
646
388
|
if (cacheEntry == null) {
|
|
647
389
|
return null;
|
|
648
390
|
}
|
|
@@ -653,334 +395,145 @@ const resultFromCachedResponse = cacheEntry => {
|
|
|
653
395
|
} = cacheEntry;
|
|
654
396
|
|
|
655
397
|
if (error != null) {
|
|
656
|
-
// Let's hydrate the error. We don't persist everything about the
|
|
657
|
-
// original error on the server, hence why we only superficially
|
|
658
|
-
// hydrate it to a GqlHydratedError.
|
|
659
398
|
return Status.error(new DataError(error, DataErrors.Hydrated));
|
|
660
399
|
}
|
|
661
400
|
|
|
662
401
|
if (data != null) {
|
|
663
402
|
return Status.success(data);
|
|
664
|
-
}
|
|
665
|
-
|
|
403
|
+
}
|
|
666
404
|
|
|
667
405
|
return Status.aborted();
|
|
668
406
|
};
|
|
669
407
|
|
|
670
|
-
|
|
671
|
-
* InterceptContext defines a map from request ID to interception methods.
|
|
672
|
-
*
|
|
673
|
-
* INTERNAL USE ONLY
|
|
674
|
-
*/
|
|
675
|
-
const InterceptContext = /*#__PURE__*/React.createContext([]);
|
|
676
|
-
|
|
677
|
-
/**
|
|
678
|
-
* Allow request handling to be intercepted.
|
|
679
|
-
*
|
|
680
|
-
* Hook to take a uniquely identified request handler and return a
|
|
681
|
-
* method that will support request interception from the InterceptRequest
|
|
682
|
-
* component.
|
|
683
|
-
*
|
|
684
|
-
* If you want request interception to be supported with `useServerEffect` or
|
|
685
|
-
* any client-side effect that uses the handler, call this first to generate
|
|
686
|
-
* an intercepted handler, and then invoke `useServerEffect` (or other things)
|
|
687
|
-
* with that intercepted handler.
|
|
688
|
-
*/
|
|
689
|
-
const useRequestInterception = (requestId, handler) => {
|
|
690
|
-
// Get the interceptors that have been registered.
|
|
691
|
-
const interceptors = React.useContext(InterceptContext); // Now, we need to create a new handler that will check if the
|
|
692
|
-
// request is intercepted before ultimately calling the original handler
|
|
693
|
-
// if nothing intercepted it.
|
|
694
|
-
// We memoize this so that it only changes if something related to it
|
|
695
|
-
// changes.
|
|
408
|
+
const InterceptContext = React.createContext([]);
|
|
696
409
|
|
|
410
|
+
const useRequestInterception = (requestId, handler) => {
|
|
411
|
+
const interceptors = React.useContext(InterceptContext);
|
|
697
412
|
const interceptedHandler = React.useCallback(() => {
|
|
698
|
-
// Call the interceptors from closest to furthest.
|
|
699
|
-
// If one returns a non-null result, then we keep that.
|
|
700
413
|
const interceptResponse = interceptors.reduceRight((prev, interceptor) => {
|
|
701
414
|
if (prev != null) {
|
|
702
415
|
return prev;
|
|
703
416
|
}
|
|
704
417
|
|
|
705
418
|
return interceptor(requestId);
|
|
706
|
-
}, null);
|
|
707
|
-
// NOTE: We can't guarantee all interceptors return the same type
|
|
708
|
-
// as our handler, so how can flow know? Let's just suppress that.
|
|
709
|
-
// $FlowFixMe[incompatible-return]
|
|
710
|
-
|
|
419
|
+
}, null);
|
|
711
420
|
return interceptResponse != null ? interceptResponse : handler();
|
|
712
421
|
}, [handler, interceptors, requestId]);
|
|
713
422
|
return interceptedHandler;
|
|
714
423
|
};
|
|
715
424
|
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
*
|
|
724
|
-
* This hook requires the Wonder Blocks Data functionality for resolving
|
|
725
|
-
* pending requests, as well as support for the hydration cache to be
|
|
726
|
-
* embedded into a page so that the result can by hydrated (if that is a
|
|
727
|
-
* requirement).
|
|
728
|
-
*
|
|
729
|
-
* The asynchronous action is never invoked on the client-side.
|
|
730
|
-
*/
|
|
731
|
-
const useServerEffect = (requestId, handler, hydrate = true) => {
|
|
732
|
-
// Plug in to the request interception framework for code that wants
|
|
733
|
-
// to use that.
|
|
734
|
-
const interceptedHandler = useRequestInterception(requestId, handler); // If we're server-side or hydrating, we'll have a cached entry to use.
|
|
735
|
-
// So we get that and use it to initialize our state.
|
|
736
|
-
// This works in both hydration and SSR because the very first call to
|
|
737
|
-
// this will have cached data in those cases as it will be present on the
|
|
738
|
-
// initial render - and subsequent renders on the client it will be null.
|
|
739
|
-
|
|
740
|
-
const cachedResult = SsrCache.Default.getEntry(requestId); // We only track data requests when we are server-side and we don't
|
|
741
|
-
// already have a result, as given by the cachedData (which is also the
|
|
742
|
-
// initial value for the result state).
|
|
743
|
-
|
|
425
|
+
const useServerEffect = (requestId, handler, options = {}) => {
|
|
426
|
+
const {
|
|
427
|
+
hydrate = true,
|
|
428
|
+
skip = false
|
|
429
|
+
} = options;
|
|
430
|
+
const interceptedHandler = useRequestInterception(requestId, handler);
|
|
431
|
+
const cachedResult = SsrCache.Default.getEntry(requestId);
|
|
744
432
|
const maybeTrack = useContext(TrackerContext);
|
|
745
433
|
|
|
746
|
-
if (cachedResult == null && Server.isServerSide()) {
|
|
434
|
+
if (!skip && cachedResult == null && Server.isServerSide()) {
|
|
747
435
|
maybeTrack == null ? void 0 : maybeTrack(requestId, interceptedHandler, hydrate);
|
|
748
|
-
}
|
|
749
|
-
|
|
436
|
+
}
|
|
750
437
|
|
|
751
438
|
return cachedResult == null ? null : resultFromCachedResponse(cachedResult);
|
|
752
439
|
};
|
|
753
440
|
|
|
754
|
-
/**
|
|
755
|
-
* This is the cache.
|
|
756
|
-
* It's incredibly complex.
|
|
757
|
-
* Very in-memory. So cache. Such complex. Wow.
|
|
758
|
-
*/
|
|
759
441
|
const cache = new ScopedInMemoryCache();
|
|
760
|
-
/**
|
|
761
|
-
* Clear the in-memory cache or a single scope within it.
|
|
762
|
-
*/
|
|
763
|
-
|
|
764
442
|
const clearSharedCache = (scope = "") => {
|
|
765
|
-
// If we have a valid scope (empty string is falsy), then clear that scope.
|
|
766
443
|
if (scope && typeof scope === "string") {
|
|
767
444
|
cache.purgeScope(scope);
|
|
768
445
|
} else {
|
|
769
|
-
// Just reset the object. This should be sufficient.
|
|
770
446
|
cache.purgeAll();
|
|
771
447
|
}
|
|
772
448
|
};
|
|
773
|
-
/**
|
|
774
|
-
* Hook to retrieve data from and store data in an in-memory cache.
|
|
775
|
-
*
|
|
776
|
-
* @returns {[?ReadOnlyCacheValue, CacheValueFn]}
|
|
777
|
-
* Returns an array containing the current cache entry (or undefined), a
|
|
778
|
-
* function to set the cache entry (passing null or undefined to this function
|
|
779
|
-
* will delete the entry).
|
|
780
|
-
*
|
|
781
|
-
* To clear a single scope within the cache or the entire cache,
|
|
782
|
-
* the `clearScopedCache` export is available.
|
|
783
|
-
*
|
|
784
|
-
* NOTE: Unlike useState or useReducer, we don't automatically update folks
|
|
785
|
-
* if the value they reference changes. We might add it later (if we need to),
|
|
786
|
-
* but the likelihood here is that things won't be changing in this cache in a
|
|
787
|
-
* way where we would need that. If we do (and likely only in specific
|
|
788
|
-
* circumstances), we should consider adding a simple boolean useState that can
|
|
789
|
-
* be toggled to cause a rerender whenever the referenced cached data changes
|
|
790
|
-
* so that callers can re-render on cache changes. However, we should make
|
|
791
|
-
* sure this toggling is optional - or we could use a callback argument, to
|
|
792
|
-
* achieve this on an as-needed basis.
|
|
793
|
-
*/
|
|
794
|
-
|
|
795
449
|
const useSharedCache = (id, scope, initialValue) => {
|
|
796
|
-
// Verify arguments.
|
|
797
450
|
if (!id || typeof id !== "string") {
|
|
798
451
|
throw new DataError("id must be a non-empty string", DataErrors.InvalidInput);
|
|
799
452
|
}
|
|
800
453
|
|
|
801
454
|
if (!scope || typeof scope !== "string") {
|
|
802
455
|
throw new DataError("scope must be a non-empty string", DataErrors.InvalidInput);
|
|
803
|
-
}
|
|
804
|
-
// This one allows callers to set or replace the cached value.
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
const cacheValue = React.useCallback(value => value == null ? cache.purge(scope, id) : cache.set(scope, id, value), [id, scope]); // We don't memo-ize the current value, just in case the cache was updated
|
|
808
|
-
// since our last run through. Also, our cache does not know what type it
|
|
809
|
-
// stores, so we have to cast it to the type we're exporting. This is a
|
|
810
|
-
// dev time courtesy, rather than a runtime thing.
|
|
811
|
-
// $FlowIgnore[incompatible-type]
|
|
456
|
+
}
|
|
812
457
|
|
|
813
|
-
|
|
814
|
-
|
|
458
|
+
const cacheValue = React.useCallback(value => value == null ? cache.purge(scope, id) : cache.set(scope, id, value), [id, scope]);
|
|
459
|
+
let currentValue = cache.get(scope, id);
|
|
815
460
|
|
|
816
461
|
if (currentValue == null && initialValue !== undefined) {
|
|
817
|
-
// Get the initial value.
|
|
818
462
|
const value = typeof initialValue === "function" ? initialValue() : initialValue;
|
|
819
463
|
|
|
820
464
|
if (value != null) {
|
|
821
|
-
|
|
822
|
-
cacheValue(value); // Make sure we return this value as our current value.
|
|
823
|
-
|
|
465
|
+
cacheValue(value);
|
|
824
466
|
currentValue = value;
|
|
825
467
|
}
|
|
826
|
-
}
|
|
827
|
-
|
|
468
|
+
}
|
|
828
469
|
|
|
829
470
|
return [currentValue, cacheValue];
|
|
830
471
|
};
|
|
831
472
|
|
|
832
473
|
const DefaultScope$1 = "useCachedEffect";
|
|
833
|
-
/**
|
|
834
|
-
* Hook to execute and cache an async operation on the client.
|
|
835
|
-
*
|
|
836
|
-
* This hook executes the given handler on the client if there is no
|
|
837
|
-
* cached result to use.
|
|
838
|
-
*
|
|
839
|
-
* Results are cached so they can be shared between equivalent invocations.
|
|
840
|
-
* In-flight requests are also shared, so that concurrent calls will
|
|
841
|
-
* behave as one might exect. Cache updates invoked by one hook instance
|
|
842
|
-
* do not trigger renders in components that use the same requestID; however,
|
|
843
|
-
* that should not matter since concurrent requests will share the same
|
|
844
|
-
* in-flight request, and subsequent renders will grab from the cache.
|
|
845
|
-
*
|
|
846
|
-
* Once the request has been tried once and a non-loading response has been
|
|
847
|
-
* cached, the request will not executed made again.
|
|
848
|
-
*/
|
|
849
|
-
|
|
850
474
|
const useCachedEffect = (requestId, handler, options = {}) => {
|
|
851
475
|
const {
|
|
852
476
|
skip: hardSkip = false,
|
|
853
477
|
retainResultOnChange = false,
|
|
854
478
|
onResultChanged,
|
|
855
479
|
scope = DefaultScope$1
|
|
856
|
-
} = options;
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
const interceptedHandler = useRequestInterception(requestId, handler); // Instead of using state, which would be local to just this hook instance,
|
|
860
|
-
// we use a shared in-memory cache.
|
|
861
|
-
|
|
862
|
-
const [mostRecentResult, setMostRecentResult] = useSharedCache(requestId, // The key of the cached item
|
|
863
|
-
scope // The scope of the cached items
|
|
864
|
-
// No default value. We don't want the loading status there; to ensure
|
|
865
|
-
// that all calls when the request is in-flight will update once that
|
|
866
|
-
// request is done, we want the cache to be empty until that point.
|
|
867
|
-
); // Build a function that will update the cache and either invoke the
|
|
868
|
-
// callback provided in options, or force an update.
|
|
869
|
-
|
|
480
|
+
} = options;
|
|
481
|
+
const interceptedHandler = useRequestInterception(requestId, handler);
|
|
482
|
+
const [mostRecentResult, setMostRecentResult] = useSharedCache(requestId, scope);
|
|
870
483
|
const forceUpdate = useForceUpdate();
|
|
871
484
|
const setCacheAndNotify = React.useCallback(value => {
|
|
872
|
-
setMostRecentResult(value);
|
|
873
|
-
// Otherwise, we toggle our little state update.
|
|
485
|
+
setMostRecentResult(value);
|
|
874
486
|
|
|
875
487
|
if (onResultChanged != null) {
|
|
876
488
|
onResultChanged(value);
|
|
877
489
|
} else {
|
|
878
490
|
forceUpdate();
|
|
879
491
|
}
|
|
880
|
-
}, [setMostRecentResult, onResultChanged, forceUpdate]);
|
|
881
|
-
// indicates its a different request. We don't default the current id as
|
|
882
|
-
// this is a proxy for the first render, where we will make the request
|
|
883
|
-
// if we don't already have a cached value.
|
|
884
|
-
|
|
492
|
+
}, [setMostRecentResult, onResultChanged, forceUpdate]);
|
|
885
493
|
const requestIdRef = React.useRef();
|
|
886
|
-
const previousRequestId = requestIdRef.current;
|
|
887
|
-
// Soft skip changes are things that should skip the effect if something
|
|
888
|
-
// else triggers the effect to run, but should not itself trigger the effect
|
|
889
|
-
// (which would cancel a previous invocation).
|
|
890
|
-
|
|
494
|
+
const previousRequestId = requestIdRef.current;
|
|
891
495
|
const softSkip = React.useMemo(() => {
|
|
892
496
|
if (requestId === previousRequestId) {
|
|
893
|
-
// If the requestId is unchanged, it means we already rendered at
|
|
894
|
-
// least once and so we already made the request at least once. So
|
|
895
|
-
// we can bail out right here.
|
|
896
497
|
return true;
|
|
897
|
-
}
|
|
898
|
-
|
|
498
|
+
}
|
|
899
499
|
|
|
900
500
|
if (mostRecentResult != null) {
|
|
901
501
|
return true;
|
|
902
502
|
}
|
|
903
503
|
|
|
904
504
|
return false;
|
|
905
|
-
}, [requestId, previousRequestId, mostRecentResult]);
|
|
906
|
-
// options.
|
|
907
|
-
|
|
505
|
+
}, [requestId, previousRequestId, mostRecentResult]);
|
|
908
506
|
React.useEffect(() => {
|
|
909
|
-
let cancel = false;
|
|
910
|
-
// means we should cancel the previous request and is therefore a
|
|
911
|
-
// dependency on that), or we have determined we have already done
|
|
912
|
-
// enough and can soft skip (a soft skip doesn't trigger the request
|
|
913
|
-
// to re-run; we don't want to cancel the in progress effect if we're
|
|
914
|
-
// soft skipping.
|
|
507
|
+
let cancel = false;
|
|
915
508
|
|
|
916
509
|
if (hardSkip || softSkip) {
|
|
917
510
|
return;
|
|
918
|
-
}
|
|
919
|
-
// Let's make sure our ref is set to the most recent requestId.
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
requestIdRef.current = requestId; // OK, we've done all our checks and things. It's time to make the
|
|
923
|
-
// request. We use our request fulfillment here so that in-flight
|
|
924
|
-
// requests are shared.
|
|
925
|
-
// NOTE: Our request fulfillment handles the error cases here.
|
|
926
|
-
// Catching shouldn't serve a purpose.
|
|
927
|
-
// eslint-disable-next-line promise/catch-or-return
|
|
511
|
+
}
|
|
928
512
|
|
|
513
|
+
requestIdRef.current = requestId;
|
|
929
514
|
RequestFulfillment.Default.fulfill(requestId, {
|
|
930
515
|
handler: interceptedHandler
|
|
931
516
|
}).then(result => {
|
|
932
517
|
if (cancel) {
|
|
933
|
-
// We don't modify our result if an earlier effect was
|
|
934
|
-
// cancelled as it means that this hook no longer cares about
|
|
935
|
-
// that old request.
|
|
936
518
|
return;
|
|
937
519
|
}
|
|
938
520
|
|
|
939
521
|
setCacheAndNotify(result);
|
|
940
|
-
return;
|
|
522
|
+
return;
|
|
941
523
|
});
|
|
942
524
|
return () => {
|
|
943
|
-
// TODO(somewhatabstract, FEI-4276): Eventually, we will want to be
|
|
944
|
-
// able abort in-flight requests, but for now, we don't have that.
|
|
945
|
-
// (Of course, we will only want to abort them if no one is waiting
|
|
946
|
-
// on them)
|
|
947
|
-
// For now, we just block cancelled requests from changing our
|
|
948
|
-
// cache.
|
|
949
525
|
cancel = true;
|
|
950
|
-
};
|
|
951
|
-
|
|
952
|
-
// cancellation of a pending request. We do not update if the handler
|
|
953
|
-
// changes, in order to simplify the API - otherwise, callers would
|
|
954
|
-
// not be able to use inline functions with this hook.
|
|
955
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
956
|
-
}, [hardSkip, requestId]); // We track the last result we returned in order to support the
|
|
957
|
-
// "retainResultOnChange" option.
|
|
958
|
-
|
|
526
|
+
};
|
|
527
|
+
}, [hardSkip, requestId]);
|
|
959
528
|
const lastResultAgnosticOfIdRef = React.useRef(Status.loading());
|
|
960
|
-
const loadingResult = retainResultOnChange ? lastResultAgnosticOfIdRef.current : Status.loading();
|
|
961
|
-
// we cache.
|
|
962
|
-
|
|
529
|
+
const loadingResult = retainResultOnChange ? lastResultAgnosticOfIdRef.current : Status.loading();
|
|
963
530
|
const result = React.useMemo(() => mostRecentResult != null ? mostRecentResult : loadingResult, [mostRecentResult, loadingResult]);
|
|
964
531
|
lastResultAgnosticOfIdRef.current = result;
|
|
965
532
|
return result;
|
|
966
533
|
};
|
|
967
534
|
|
|
968
|
-
/**
|
|
969
|
-
* Policies to define how a hydratable effect should behave client-side.
|
|
970
|
-
*/
|
|
971
535
|
const WhenClientSide = require("flow-enums-runtime").Mirrored(["DoNotHydrate", "ExecuteWhenNoResult", "ExecuteWhenNoSuccessResult", "AlwaysExecute"]);
|
|
972
536
|
const DefaultScope = "useHydratableEffect";
|
|
973
|
-
/**
|
|
974
|
-
* Hook to execute an async operation on server and client.
|
|
975
|
-
*
|
|
976
|
-
* This hook executes the given handler on the server and on the client,
|
|
977
|
-
* and, depending on the given options, can hydrate the server-side result.
|
|
978
|
-
*
|
|
979
|
-
* Results are cached on the client so they can be shared between equivalent
|
|
980
|
-
* invocations. Cache changes from one hook instance do not trigger renders
|
|
981
|
-
* in components that use the same requestID.
|
|
982
|
-
*/
|
|
983
|
-
|
|
984
537
|
const useHydratableEffect = (requestId, handler, options = {}) => {
|
|
985
538
|
const {
|
|
986
539
|
clientBehavior = WhenClientSide.ExecuteWhenNoSuccessResult,
|
|
@@ -988,68 +541,38 @@ const useHydratableEffect = (requestId, handler, options = {}) => {
|
|
|
988
541
|
retainResultOnChange = false,
|
|
989
542
|
onResultChanged,
|
|
990
543
|
scope = DefaultScope
|
|
991
|
-
} = options;
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
// just give an aborted response.
|
|
997
|
-
skip ? () => Promise.reject(new AbortError("skipped")) : handler, // Only hydrate if our behavior isn't telling us not to.
|
|
998
|
-
clientBehavior !== WhenClientSide.DoNotHydrate);
|
|
544
|
+
} = options;
|
|
545
|
+
const serverResult = useServerEffect(requestId, handler, {
|
|
546
|
+
hydrate: clientBehavior !== WhenClientSide.DoNotHydrate,
|
|
547
|
+
skip
|
|
548
|
+
});
|
|
999
549
|
const getDefaultCacheValue = React.useCallback(() => {
|
|
1000
|
-
// If we don't have a requestId, it's our first render, the one
|
|
1001
|
-
// where we hydrated. So defer to our clientBehavior value.
|
|
1002
550
|
switch (clientBehavior) {
|
|
1003
551
|
case WhenClientSide.DoNotHydrate:
|
|
1004
552
|
case WhenClientSide.AlwaysExecute:
|
|
1005
|
-
// Either we weren't hydrating at all, or we don't care
|
|
1006
|
-
// if we hydrated something or not, either way, we're
|
|
1007
|
-
// doing a request.
|
|
1008
553
|
return null;
|
|
1009
554
|
|
|
1010
555
|
case WhenClientSide.ExecuteWhenNoResult:
|
|
1011
|
-
// We only execute if we didn't hydrate something.
|
|
1012
|
-
// So, returning the hydration result as default for our
|
|
1013
|
-
// cache, will then prevent the cached effect running.
|
|
1014
556
|
return serverResult;
|
|
1015
557
|
|
|
1016
558
|
case WhenClientSide.ExecuteWhenNoSuccessResult:
|
|
1017
|
-
// We only execute if we didn't hydrate a success result.
|
|
1018
559
|
if ((serverResult == null ? void 0 : serverResult.status) === "success") {
|
|
1019
|
-
// So, returning the hydration result as default for our
|
|
1020
|
-
// cache, will then prevent the cached effect running.
|
|
1021
560
|
return serverResult;
|
|
1022
561
|
}
|
|
1023
562
|
|
|
1024
563
|
return null;
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
}, []); // Instead of using state, which would be local to just this hook instance,
|
|
1029
|
-
// we use a shared in-memory cache.
|
|
1030
|
-
|
|
1031
|
-
useSharedCache(requestId, // The key of the cached item
|
|
1032
|
-
scope, // The scope of the cached items
|
|
1033
|
-
getDefaultCacheValue); // When we're client-side, we ultimately want the result from this call.
|
|
1034
|
-
|
|
564
|
+
}
|
|
565
|
+
}, [serverResult]);
|
|
566
|
+
useSharedCache(requestId, scope, getDefaultCacheValue);
|
|
1035
567
|
const clientResult = useCachedEffect(requestId, handler, {
|
|
1036
568
|
skip,
|
|
1037
569
|
onResultChanged,
|
|
1038
570
|
retainResultOnChange,
|
|
1039
571
|
scope
|
|
1040
|
-
});
|
|
1041
|
-
// Well, we return the serverResult on our very first call and then
|
|
1042
|
-
// the clientResult thereafter. The great thing is that after the very
|
|
1043
|
-
// first call, the serverResult is going to be `null` anyway.
|
|
1044
|
-
|
|
572
|
+
});
|
|
1045
573
|
return serverResult != null ? serverResult : clientResult;
|
|
1046
574
|
};
|
|
1047
575
|
|
|
1048
|
-
/**
|
|
1049
|
-
* This component is the main component of Wonder Blocks Data. With this, data
|
|
1050
|
-
* requirements can be placed in a React application in a manner that will
|
|
1051
|
-
* support server-side rendering and efficient caching.
|
|
1052
|
-
*/
|
|
1053
576
|
const Data = ({
|
|
1054
577
|
requestId,
|
|
1055
578
|
handler,
|
|
@@ -1064,87 +587,39 @@ const Data = ({
|
|
|
1064
587
|
return children(result);
|
|
1065
588
|
};
|
|
1066
589
|
|
|
1067
|
-
/**
|
|
1068
|
-
* This component provides a mechanism to intercept data requests.
|
|
1069
|
-
* This is for use in testing.
|
|
1070
|
-
*
|
|
1071
|
-
* This component is not recommended for use in production code as it
|
|
1072
|
-
* can prevent predictable functioning of the Wonder Blocks Data framework.
|
|
1073
|
-
* One possible side-effect is that inflight requests from the interceptor could
|
|
1074
|
-
* be picked up by `Data` component requests from outside the children of this
|
|
1075
|
-
* component.
|
|
1076
|
-
*
|
|
1077
|
-
* Interceptions within the same component tree are chained such that the
|
|
1078
|
-
* interceptor closest to the intercepted request is called first, and the
|
|
1079
|
-
* furthest interceptor is called last.
|
|
1080
|
-
*/
|
|
1081
590
|
const InterceptRequests = ({
|
|
1082
591
|
interceptor,
|
|
1083
592
|
children
|
|
1084
593
|
}) => {
|
|
1085
594
|
const interceptors = React.useContext(InterceptContext);
|
|
1086
|
-
const updatedInterceptors = React.useMemo(
|
|
1087
|
-
|
|
1088
|
-
// is easier to think about if we do this in component tree order.
|
|
1089
|
-
() => [].concat(interceptors, [interceptor]), [interceptors, interceptor]);
|
|
1090
|
-
return /*#__PURE__*/React.createElement(InterceptContext.Provider, {
|
|
595
|
+
const updatedInterceptors = React.useMemo(() => [].concat(interceptors, [interceptor]), [interceptors, interceptor]);
|
|
596
|
+
return React.createElement(InterceptContext.Provider, {
|
|
1091
597
|
value: updatedInterceptors
|
|
1092
598
|
}, children);
|
|
1093
599
|
};
|
|
1094
600
|
|
|
1095
|
-
const GqlRouterContext =
|
|
601
|
+
const GqlRouterContext = React.createContext(null);
|
|
1096
602
|
|
|
1097
|
-
/**
|
|
1098
|
-
* Configure GraphQL routing for GraphQL hooks and components.
|
|
1099
|
-
*
|
|
1100
|
-
* These can be nested. Components and hooks relying on the GraphQL routing
|
|
1101
|
-
* will use the configuration from their closest ancestral GqlRouter.
|
|
1102
|
-
*/
|
|
1103
603
|
const GqlRouter = ({
|
|
1104
604
|
defaultContext: thisDefaultContext,
|
|
1105
605
|
fetch: thisFetch,
|
|
1106
606
|
children
|
|
1107
607
|
}) => {
|
|
1108
|
-
// We don't care if we're nested. We always force our callers to define
|
|
1109
|
-
// everything. It makes for a clearer API and requires less error checking
|
|
1110
|
-
// code (assuming our flow types are correct). We also don't default fetch
|
|
1111
|
-
// to anything - our callers can tell us what function to use quite easily.
|
|
1112
|
-
// If code that consumes this wants more nuanced nesting, it can implement
|
|
1113
|
-
// it within its own GqlRouter than then defers to this one.
|
|
1114
|
-
// We want to always use the same object if things haven't changed to avoid
|
|
1115
|
-
// over-rendering consumers of our context, let's memoize the configuration.
|
|
1116
|
-
// By doing this, if a component under children that uses this context
|
|
1117
|
-
// uses React.memo, we won't force it to re-render every time we render
|
|
1118
|
-
// because we'll only change the context value if something has actually
|
|
1119
|
-
// changed.
|
|
1120
608
|
const configuration = React.useMemo(() => ({
|
|
1121
609
|
fetch: thisFetch,
|
|
1122
610
|
defaultContext: thisDefaultContext
|
|
1123
611
|
}), [thisDefaultContext, thisFetch]);
|
|
1124
|
-
return
|
|
612
|
+
return React.createElement(GqlRouterContext.Provider, {
|
|
1125
613
|
value: configuration
|
|
1126
614
|
}, children);
|
|
1127
615
|
};
|
|
1128
616
|
|
|
1129
|
-
/**
|
|
1130
|
-
* Construct a complete GqlContext from current defaults and a partial context.
|
|
1131
|
-
*
|
|
1132
|
-
* Values in the partial context that are `undefined` will be ignored.
|
|
1133
|
-
* Values in the partial context that are `null` will be deleted.
|
|
1134
|
-
*/
|
|
1135
617
|
const mergeGqlContext = (defaultContext, overrides) => {
|
|
1136
|
-
// Let's merge the partial context default context. We deliberately
|
|
1137
|
-
// don't spread because spreading would overwrite default context
|
|
1138
|
-
// values with undefined or null if the partial context includes a value
|
|
1139
|
-
// explicitly set to undefined or null.
|
|
1140
618
|
return Object.keys(overrides).reduce((acc, key) => {
|
|
1141
|
-
// Undefined values are ignored.
|
|
1142
619
|
if (overrides[key] !== undefined) {
|
|
1143
620
|
if (overrides[key] === null) {
|
|
1144
|
-
// Null indicates we delete this context value.
|
|
1145
621
|
delete acc[key];
|
|
1146
622
|
} else {
|
|
1147
|
-
// Otherwise, we set it.
|
|
1148
623
|
acc[key] = overrides[key];
|
|
1149
624
|
}
|
|
1150
625
|
}
|
|
@@ -1153,32 +628,11 @@ const mergeGqlContext = (defaultContext, overrides) => {
|
|
|
1153
628
|
}, _extends({}, defaultContext));
|
|
1154
629
|
};
|
|
1155
630
|
|
|
1156
|
-
/**
|
|
1157
|
-
* Error kinds for GqlError.
|
|
1158
|
-
*/
|
|
1159
631
|
const GqlErrors = Object.freeze({
|
|
1160
|
-
/**
|
|
1161
|
-
* An internal framework error.
|
|
1162
|
-
*/
|
|
1163
632
|
Internal: "Internal",
|
|
1164
|
-
|
|
1165
|
-
/**
|
|
1166
|
-
* Response does not have the correct structure for a GraphQL response.
|
|
1167
|
-
*/
|
|
1168
633
|
BadResponse: "BadResponse",
|
|
1169
|
-
|
|
1170
|
-
/**
|
|
1171
|
-
* A valid GraphQL result with errors field in the payload.
|
|
1172
|
-
*/
|
|
1173
634
|
ErrorResult: "ErrorResult"
|
|
1174
635
|
});
|
|
1175
|
-
/**
|
|
1176
|
-
* An error from the GQL API.
|
|
1177
|
-
*
|
|
1178
|
-
* Errors of this type will have names of the format:
|
|
1179
|
-
* `${kind}GqlError`
|
|
1180
|
-
*/
|
|
1181
|
-
|
|
1182
636
|
class GqlError extends KindError {
|
|
1183
637
|
constructor(message, kind, {
|
|
1184
638
|
metadata,
|
|
@@ -1193,11 +647,7 @@ class GqlError extends KindError {
|
|
|
1193
647
|
|
|
1194
648
|
}
|
|
1195
649
|
|
|
1196
|
-
/**
|
|
1197
|
-
* Construct a GqlRouterContext from the current one and partial context.
|
|
1198
|
-
*/
|
|
1199
650
|
const useGqlRouterContext = (contextOverrides = {}) => {
|
|
1200
|
-
// This hook only works if the `GqlRouter` has been used to setup context.
|
|
1201
651
|
const gqlRouterContext = useContext(GqlRouterContext);
|
|
1202
652
|
|
|
1203
653
|
if (gqlRouterContext == null) {
|
|
@@ -1209,17 +659,14 @@ const useGqlRouterContext = (contextOverrides = {}) => {
|
|
|
1209
659
|
defaultContext
|
|
1210
660
|
} = gqlRouterContext;
|
|
1211
661
|
const contextRef = useRef(defaultContext);
|
|
1212
|
-
const mergedContext = mergeGqlContext(defaultContext, contextOverrides);
|
|
1213
|
-
// update our ref and return the merged value.
|
|
1214
|
-
|
|
662
|
+
const mergedContext = mergeGqlContext(defaultContext, contextOverrides);
|
|
1215
663
|
const refKeys = Object.keys(contextRef.current);
|
|
1216
664
|
const mergedKeys = Object.keys(mergedContext);
|
|
1217
665
|
const shouldWeUpdateRef = refKeys.length !== mergedKeys.length || mergedKeys.every(key => contextRef.current[key] !== mergedContext[key]);
|
|
1218
666
|
|
|
1219
667
|
if (shouldWeUpdateRef) {
|
|
1220
668
|
contextRef.current = mergedContext;
|
|
1221
|
-
}
|
|
1222
|
-
|
|
669
|
+
}
|
|
1223
670
|
|
|
1224
671
|
const finalContext = contextRef.current;
|
|
1225
672
|
const finalRouterContext = useMemo(() => ({
|
|
@@ -1229,13 +676,7 @@ const useGqlRouterContext = (contextOverrides = {}) => {
|
|
|
1229
676
|
return finalRouterContext;
|
|
1230
677
|
};
|
|
1231
678
|
|
|
1232
|
-
/**
|
|
1233
|
-
* Validate a GQL operation response and extract the data.
|
|
1234
|
-
*/
|
|
1235
|
-
|
|
1236
679
|
const getGqlDataFromResponse = async response => {
|
|
1237
|
-
// Get the response as text, that way we can use the text in error
|
|
1238
|
-
// messaging, should our parsing fail.
|
|
1239
680
|
const bodyText = await response.text();
|
|
1240
681
|
let result;
|
|
1241
682
|
|
|
@@ -1249,8 +690,7 @@ const getGqlDataFromResponse = async response => {
|
|
|
1249
690
|
},
|
|
1250
691
|
cause: e
|
|
1251
692
|
});
|
|
1252
|
-
}
|
|
1253
|
-
|
|
693
|
+
}
|
|
1254
694
|
|
|
1255
695
|
if (response.status >= 300) {
|
|
1256
696
|
throw new DataError("Response unsuccessful", DataErrors.Network, {
|
|
@@ -1259,22 +699,16 @@ const getGqlDataFromResponse = async response => {
|
|
|
1259
699
|
result
|
|
1260
700
|
}
|
|
1261
701
|
});
|
|
1262
|
-
}
|
|
1263
|
-
|
|
702
|
+
}
|
|
1264
703
|
|
|
1265
|
-
if (
|
|
1266
|
-
// $FlowIgnore[method-unbinding]
|
|
1267
|
-
!Object.prototype.hasOwnProperty.call(result, "data") && // Flow shouldn't be warning about this.
|
|
1268
|
-
// $FlowIgnore[method-unbinding]
|
|
1269
|
-
!Object.prototype.hasOwnProperty.call(result, "errors")) {
|
|
704
|
+
if (!Object.prototype.hasOwnProperty.call(result, "data") && !Object.prototype.hasOwnProperty.call(result, "errors")) {
|
|
1270
705
|
throw new GqlError("Server response missing", GqlErrors.BadResponse, {
|
|
1271
706
|
metadata: {
|
|
1272
707
|
statusCode: response.status,
|
|
1273
708
|
result
|
|
1274
709
|
}
|
|
1275
710
|
});
|
|
1276
|
-
}
|
|
1277
|
-
|
|
711
|
+
}
|
|
1278
712
|
|
|
1279
713
|
if (result.errors != null && Array.isArray(result.errors) && result.errors.length > 0) {
|
|
1280
714
|
throw new GqlError("GraphQL errors", GqlErrors.ErrorResult, {
|
|
@@ -1283,30 +717,13 @@ const getGqlDataFromResponse = async response => {
|
|
|
1283
717
|
result
|
|
1284
718
|
}
|
|
1285
719
|
});
|
|
1286
|
-
}
|
|
1287
|
-
|
|
720
|
+
}
|
|
1288
721
|
|
|
1289
722
|
return result.data;
|
|
1290
723
|
};
|
|
1291
724
|
|
|
1292
|
-
/**
|
|
1293
|
-
* Hook to obtain a gqlFetch function for performing GraphQL requests.
|
|
1294
|
-
*
|
|
1295
|
-
* The fetch function will resolve null if the request was aborted, otherwise
|
|
1296
|
-
* it will resolve the data returned by the GraphQL server.
|
|
1297
|
-
*
|
|
1298
|
-
* Context is merged with the default context provided to the GqlRouter.
|
|
1299
|
-
* Values in the partial context given to the returned fetch function will
|
|
1300
|
-
* only be included if they have a value other than undefined.
|
|
1301
|
-
*/
|
|
1302
725
|
const useGql = (context = {}) => {
|
|
1303
|
-
|
|
1304
|
-
const gqlRouterContext = useGqlRouterContext(context); // Let's memoize the gqlFetch function we create based off our context.
|
|
1305
|
-
// That way, even if the context happens to change, if its values don't
|
|
1306
|
-
// we give the same function instance back to our callers instead of
|
|
1307
|
-
// making a new one. That then means they can safely use the return value
|
|
1308
|
-
// in hooks deps without fear of it triggering extra renders.
|
|
1309
|
-
|
|
726
|
+
const gqlRouterContext = useGqlRouterContext(context);
|
|
1310
727
|
const gqlFetch = useCallback((operation, options = Object.freeze({})) => {
|
|
1311
728
|
const {
|
|
1312
729
|
fetch,
|
|
@@ -1316,31 +733,13 @@ const useGql = (context = {}) => {
|
|
|
1316
733
|
variables,
|
|
1317
734
|
context = {}
|
|
1318
735
|
} = options;
|
|
1319
|
-
const finalContext = mergeGqlContext(defaultContext, context);
|
|
1320
|
-
|
|
736
|
+
const finalContext = mergeGqlContext(defaultContext, context);
|
|
1321
737
|
return fetch(operation, variables, finalContext).then(getGqlDataFromResponse);
|
|
1322
738
|
}, [gqlRouterContext]);
|
|
1323
739
|
return gqlFetch;
|
|
1324
740
|
};
|
|
1325
741
|
|
|
1326
|
-
/**
|
|
1327
|
-
* Initialize the hydration cache.
|
|
1328
|
-
*
|
|
1329
|
-
* @param {ResponseCache} source The cache content to use for initializing the
|
|
1330
|
-
* cache.
|
|
1331
|
-
* @throws {Error} If the cache is already initialized.
|
|
1332
|
-
*/
|
|
1333
742
|
const initializeCache = source => SsrCache.Default.initialize(source);
|
|
1334
|
-
/**
|
|
1335
|
-
* Fulfill all tracked data requests.
|
|
1336
|
-
*
|
|
1337
|
-
* This is for use with the `TrackData` component during server-side rendering.
|
|
1338
|
-
*
|
|
1339
|
-
* @throws {Error} If executed outside of server-side rendering.
|
|
1340
|
-
* @returns {Promise<void>} A promise that resolves when all tracked requests
|
|
1341
|
-
* have been fulfilled.
|
|
1342
|
-
*/
|
|
1343
|
-
|
|
1344
743
|
const fulfillAllDataRequests = () => {
|
|
1345
744
|
if (!Server.isServerSide()) {
|
|
1346
745
|
return Promise.reject(new Error("Data requests are not tracked when client-side"));
|
|
@@ -1348,16 +747,6 @@ const fulfillAllDataRequests = () => {
|
|
|
1348
747
|
|
|
1349
748
|
return RequestTracker.Default.fulfillTrackedRequests();
|
|
1350
749
|
};
|
|
1351
|
-
/**
|
|
1352
|
-
* Indicate if there are unfulfilled tracked requests.
|
|
1353
|
-
*
|
|
1354
|
-
* This is used in conjunction with `TrackData`.
|
|
1355
|
-
*
|
|
1356
|
-
* @throws {Error} If executed outside of server-side rendering.
|
|
1357
|
-
* @returns {boolean} `true` if there are unfulfilled tracked requests;
|
|
1358
|
-
* otherwise, `false`.
|
|
1359
|
-
*/
|
|
1360
|
-
|
|
1361
750
|
const hasUnfulfilledRequests = () => {
|
|
1362
751
|
if (!Server.isServerSide()) {
|
|
1363
752
|
throw new Error("Data requests are not tracked when client-side");
|
|
@@ -1365,21 +754,7 @@ const hasUnfulfilledRequests = () => {
|
|
|
1365
754
|
|
|
1366
755
|
return RequestTracker.Default.hasUnfulfilledRequests;
|
|
1367
756
|
};
|
|
1368
|
-
/**
|
|
1369
|
-
* Remove the request identified from the cached hydration responses.
|
|
1370
|
-
*
|
|
1371
|
-
* @param {string} id The request ID of the response to remove from the cache.
|
|
1372
|
-
*/
|
|
1373
|
-
|
|
1374
757
|
const removeFromCache = id => SsrCache.Default.remove(id);
|
|
1375
|
-
/**
|
|
1376
|
-
* Remove all cached hydration responses that match the given predicate.
|
|
1377
|
-
*
|
|
1378
|
-
* @param {(id: string) => boolean} [predicate] The predicate to match against
|
|
1379
|
-
* the cached hydration responses. If no predicate is provided, all cached
|
|
1380
|
-
* hydration responses will be removed.
|
|
1381
|
-
*/
|
|
1382
|
-
|
|
1383
758
|
const removeAllFromCache = predicate => SsrCache.Default.removeAll(predicate);
|
|
1384
759
|
|
|
1385
760
|
export { Data, DataError, DataErrors, GqlError, GqlErrors, GqlRouter, InterceptRequests, RequestFulfillment, ScopedInMemoryCache, SerializableInMemoryCache, Status, TrackData, WhenClientSide, clearSharedCache, fulfillAllDataRequests, hasUnfulfilledRequests, initializeCache, removeAllFromCache, removeFromCache, useCachedEffect, useGql, useHydratableEffect, useServerEffect, useSharedCache };
|