resourcerer 1.2.2 → 2.0.0-beta

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.
Files changed (59) hide show
  1. package/README.md +138 -164
  2. package/build/index.d.ts +9 -0
  3. package/build/index.js +9 -0
  4. package/build/lib/collection.d.ts +107 -0
  5. package/build/lib/collection.js +251 -0
  6. package/build/lib/config.d.ts +20 -0
  7. package/build/lib/config.js +23 -0
  8. package/build/lib/error-boundary.d.ts +12 -0
  9. package/build/lib/error-boundary.js +18 -0
  10. package/build/lib/events.d.ts +11 -0
  11. package/build/lib/events.js +12 -0
  12. package/build/lib/model-cache.d.ts +13 -0
  13. package/build/lib/model-cache.js +62 -0
  14. package/build/lib/model.d.ts +48 -0
  15. package/build/lib/model.js +170 -0
  16. package/build/lib/prefetch.d.ts +3 -0
  17. package/build/lib/prefetch.js +27 -0
  18. package/build/lib/request.d.ts +20 -0
  19. package/build/lib/request.js +53 -0
  20. package/build/lib/resourcerer.d.ts +13 -0
  21. package/build/lib/resourcerer.js +406 -0
  22. package/build/lib/sync.d.ts +18 -0
  23. package/build/lib/sync.js +58 -0
  24. package/build/lib/types.d.ts +66 -0
  25. package/build/lib/types.js +1 -0
  26. package/build/lib/utils.d.ts +14 -0
  27. package/build/lib/utils.js +87 -0
  28. package/docs/advanced_topics.md +9 -77
  29. package/docs/collection.md +28 -28
  30. package/docs/migrating_to_2.0.md +72 -0
  31. package/docs/model.md +21 -21
  32. package/docs/typescript.md +68 -20
  33. package/package.json +27 -30
  34. package/resourcerer.d.ts +50 -0
  35. package/test/collection.test.js +305 -316
  36. package/test/config.test.js +21 -75
  37. package/test/events.test.js +42 -41
  38. package/test/model-cache.test.js +99 -77
  39. package/test/model.test.js +204 -209
  40. package/test/prefetch.test.js +35 -61
  41. package/test/request.test.js +104 -109
  42. package/test/sync.test.js +132 -107
  43. package/test/utils.test.js +173 -159
  44. package/index.d.ts +0 -269
  45. package/index.js +0 -14
  46. package/lib/collection.js +0 -584
  47. package/lib/config.js +0 -131
  48. package/lib/constants.js +0 -6
  49. package/lib/error-boundary.js +0 -47
  50. package/lib/events.js +0 -19
  51. package/lib/model-cache.js +0 -131
  52. package/lib/model.js +0 -372
  53. package/lib/prefetch.js +0 -59
  54. package/lib/request.js +0 -126
  55. package/lib/resourcerer.js +0 -963
  56. package/lib/sync.js +0 -94
  57. package/lib/utils.js +0 -220
  58. package/test/model-mocks.js +0 -110
  59. package/test/setup.js +0 -63
@@ -1,963 +0,0 @@
1
- import {hasErrored, hasLoaded, isLoading} from './utils.js';
2
- import {ModelMap, ResourceKeys, ResourcesConfig, UnfetchedResources} from './config.js';
3
- /* eslint-disable no-unused-vars */
4
- import React, {useEffect, useReducer, useRef, useState} from 'react';
5
- /* eslint-enable no-unused-vars */
6
-
7
- import Collection from './collection.js';
8
- import ErrorBoundary from './error-boundary.js';
9
- import {LoadingStates} from './constants.js';
10
- import Model from './model.js';
11
- import ModelCache from './model-cache.js';
12
- import ReactDOM from 'react-dom';
13
- import request from './request.js';
14
-
15
- const SPREAD_PROVIDES_CHAR = '_';
16
-
17
- /**
18
- * The useResources hook handles several different data-related things for a component
19
- * automatically:
20
- *
21
- * 1. it fetches a component's resources after mounting
22
- * 2. it binds listeners to all resources
23
- * 3. it handles whether or not the critical resources for a component have loaded
24
- * 4. it re-fetches a new resource when specified props have changed
25
- * 5. it handles resource cache naming for the ModelCache
26
- *
27
- * getResources is a function that takes props as an argument and should return
28
- * a map of resources. Each resource map key is the name of the resource (which
29
- * should be a ResourceKeys entry that also has an entry in ModelMap, but can be a
30
- * custom name if passed a modelKey config property), and each map value is a
31
- * config object that may contain any of the following properties:
32
- *
33
- * * noncritical {boolean} - whether the resource should not be taken into
34
- * account when determining the loading state of the component. default
35
- * is false
36
- * * params {object} - query params for the fetch call passed to the `request`
37
- * * options {object} - instance properties set on the model (which are not data)
38
- * * dependsOn {string[]} - prop fields required to be present before the
39
- * resource will fetch
40
- * * provides {object<string: function>[]} - list of props that a resource
41
- * provides, for example, for dependent resources (serial requests). Each
42
- * key in the object is the prop field, and its value is a transform
43
- * function that takes the model and props as arguments and should return
44
- * a value to be set for the prop. If the key is equal to
45
- * SPREAD_PROVIDES_CHAR, then the return value of the transform function
46
- * is spread for dynamically-provided props.
47
- * * force {boolean} - force a fetch request on mount regardless of whether the
48
- * model is already in the cache
49
- * * prefetch {object} - an individual map of expected future props to fetch
50
- * a new resource and store it in the cache. it will not, however, get
51
- * passed down to the child (no loading states, either)
52
- * * prefetches {object[]} - a list of objects whose properties represent the
53
- * expected future values of props. these get turned into new cache keys
54
- * and new requests.
55
- * * modelKey {ResourceKeys} - use this when adding a custom name for the resource,
56
- * so the props use the custom name, but the correct resource type is
57
- * fetched and cached
58
- * * ...any other option that can be passed directly to the `request` function
59
- */
60
- export const useResources = (getResources, props) => {
61
- var [resourceState, setResourceState] = useState({}),
62
- props = {...props, ...resourceState},
63
- resources = generateResources(getResources, props),
64
-
65
- initialLoadingStates = buildResourcesLoadingState(resources.filter(withoutPrefetch), props),
66
-
67
- // set initial loading states and create loaderDispatch for maintaining them
68
- [{loadingStates, requestStatuses, hasInitiallyLoaded}, loaderDispatch] = useReducer(
69
- loaderReducer,
70
- {
71
- loadingStates: initialLoadingStates,
72
- requestStatuses: {},
73
- hasInitiallyLoaded: hasLoaded(getCriticalLoadingStates(initialLoadingStates, resources))
74
- }
75
- ),
76
- criticalLoadingStates = getCriticalLoadingStates(loadingStates, resources),
77
-
78
- // we need to save our models as state using hooks because we can't defer
79
- // reading from the model cache with updated props, and so we'd _always_
80
- // show an empty model as a resource is being requested instead of
81
- // continuing to show the previous model. on the plus side, setting them
82
- // as state means we won't need a loading overlay component to do this for us
83
- [models, setModels] = useState(modelAggregator(resources.filter(withoutPrefetch))),
84
-
85
- isMountedRef = useIsMounted(false),
86
- // this is used as an identifier to this component instance to register
87
- // with the ModelCache. it should be constant across renders, sow keep it in a ref.
88
- componentRef = useRef({}),
89
- // this reference to previous props allows us to know when resources are changing
90
- prevPropsRef = useRef(null),
91
- // this might look confusing but is important. we need to know, before
92
- // setting any loaded or error states, that a returned resource belongs
93
- // to the most recent component props. so we use a ref to persist across the closure
94
- currentPropsRef = useRef(props),
95
- // stash reference to all models with listeners currently attached, since when we return
96
- // from any updated requests there's no guarantee that the most recent models were a
97
- // function of the previous props (as opposed to props from two renders ago, for example).
98
- // an edge case may be seen with resources that become pending or go from pending across
99
- // renders. using this reference will guarantee that we always remove listeners from the
100
- // correct models before attaching new listeners
101
- listenedModelsRef = useRef([]),
102
- // when props change and we have models ready in the cache, we set model state in the render
103
- // process. that means we re-run this function without calling any useEffect callbacks. since
104
- // prevProps will not (and should not) have changed, the same models that we're to be updated
105
- // as state in the first render phase would also be up for update in the next one. so we have
106
- // to keep track of which models have been updated in state, and then we'll reset this when
107
- // useEffect is finally called.
108
- cachedModelsSinceLastEffect = useRef({}),
109
-
110
- forceUpdate = useForceUpdate(),
111
-
112
- // note that this only tells when cache keys have changed. if a resource has already been
113
- // cached, this will still return its resource when the component mounts. that's why we
114
- // partition these out later into loaded and not loaded resources.
115
- //
116
- // for a similar reason, forced resources get returned here on mount and not afterwards.
117
- // we prevent them from getting set to a LOADED state which forces them to get fetched.
118
- getResourcesToUpdate = (rsrcs) => rsrcs.filter(hasAllDependencies.bind(null, props))
119
- .filter(not(shouldBypassFetch.bind(null, props)))
120
- .filter(([name, config]) => {
121
- var prevConfig = prevPropsRef.current &&
122
- findConfig([name, config], getResources, prevPropsRef.current),
123
- previousCacheKey = prevConfig && getCacheKey(prevConfig);
124
-
125
- return (!previousCacheKey || previousCacheKey !== getCacheKey(config) ||
126
- !hasAllDependencies(prevPropsRef.current, [, config]) || config.refetch ||
127
- // make sure if we were lazy and are no longer lazy (from the same component) that we
128
- // get included in the list to get updated (and vice versa)
129
- (prevConfig?.lazy !== config.lazy));
130
- }),
131
-
132
- // every time we call this, we remove all previous listeners and attach new ones based on the
133
- // current models used by the component.
134
- attachModelListeners = () => {
135
- // only get those from the cache. models in state might can empty models, but even so i
136
- // think it would be preferable to use state (within a separate useEffect) to determine
137
- // which models get listened to. but as mentioned, that would require the effect to depend
138
- // on cache keys, which are dynamic, and effects can't have dynamic dependencies right now
139
- let listenedModels = resources.map(([, config]) => getModelFromCache(config))
140
- .filter(Boolean);
141
-
142
- // remove previous listeners and attach new ones
143
- listenedModelsRef.current.forEach((model) => model.offUpdate(componentRef.current));
144
- listenedModels.forEach((model) => model.onUpdate(forceUpdate, componentRef.current));
145
-
146
- listenedModelsRef.current = listenedModels;
147
- },
148
-
149
- // this should be for NEW pending resources only, not ones set in initial loading state
150
- pendingResources = resources.filter(not(hasAllDependencies.bind(null, props)))
151
- .filter(([, config]) =>
152
- prevPropsRef.current && hasAllDependencies(prevPropsRef.current, [, config])),
153
- resourcesToUpdate = getResourcesToUpdate(resources),
154
- nextLoadingStates = {
155
- ...buildResourcesLoadingState(pendingResources, props, LoadingStates.PENDING),
156
- // but resourcesToUpdate should get set to LOADING (or LOADED if in the cache)
157
- ...buildResourcesLoadingState(
158
- // removing forced resources here ensures that they stay in a LOADING state and thus
159
- // get partitioned into resourcesToFetch. this only happens on mount; on update, they
160
- // don't ever get included in resourcesToUpdate
161
- resourcesToUpdate.filter(withoutPrefetch).filter(withoutForced),
162
- props
163
- )
164
- },
165
-
166
- // separate out those resources to update into those that are already cached and those
167
- // that need to be fetched. the former will get the models updated immediately
168
- [loadedResources, resourcesToFetch] = partitionResources(
169
- resourcesToUpdate,
170
- nextLoadingStates
171
- ),
172
-
173
- // "cached" is a misnomer...
174
- cachedResources = pendingResources.concat(loadedResources)
175
- .filter(([name]) => !cachedModelsSinceLastEffect.current[name]);
176
-
177
- // here we set any newly-pending resources as well as any already-loaded resources as model state,
178
- // short-circuiting the render cycle since this update happens in the render phase. this is a
179
- // critical piece of useResources because it means that models, dependent models, and also loading
180
- // states (next block of code) get updated immediately with no extra 'in-between' blips on the
181
- // screen.
182
- if (cachedResources.length) {
183
- setModels(modelAggregator(cachedResources));
184
- cachedResources.forEach(([name, config]) => {
185
- cachedModelsSinceLastEffect.current[name] = true;
186
- });
187
-
188
- // because we don't go through the request module for normal-flow resources that are cached,
189
- // we need to re-register this component with the resource. this will also clear any timeouts
190
- // for removing the resource.
191
- loadedResources.forEach(([, config]) => {
192
- var cacheKey = getCacheKey(config);
193
-
194
- ModelCache.register(cacheKey, componentRef.current);
195
- // make sure we add any provided props for serial requests. when this function rerenders any
196
- // cached dependent models will also trigger a setModels call and an additional re-render
197
- // without a useEffect
198
- provideProps(ModelCache.get(cacheKey), config.provides, props, setResourceState);
199
- });
200
-
201
- // make sure if we bypass fetching because of cached models that we attach fresh listeners
202
- attachModelListeners();
203
- }
204
-
205
- // set our updated resources' loading states to LOADING. but don't set if we're already in a
206
- // loading state for that resource, because that's a pointless extra render. also, any resources
207
- // that have lost their dependencies should go back to a pending state.
208
- if (Object.keys(nextLoadingStates).some((ky) => nextLoadingStates[ky] !== loadingStates[ky])) {
209
- loaderDispatch({type: LoadingStates.LOADING, payload: nextLoadingStates});
210
- }
211
-
212
- /**
213
- * Fetch things.
214
- *
215
- * Note also that every time we set a state, whether it be loading states or models, we are
216
- * setting a new object as that state and we will re-render. That means that if a model is cached
217
- * or its loading states haven't changed we should _not_ just go ahead and call fetchResources,
218
- * because that will re-render our components an additional two times.
219
- */
220
- useEffect(() => {
221
- // NOTE: changing this to resourcesToFetch causes some inexplicable bugs around cached resources
222
- // and a UI that wouldn't update. so this is kept as resourcesToUpdate and fetchResources is
223
- // given resourcesToFetch. Because we are still only fetching resourcesToFetch and because any
224
- // loaded resources will have already had their models set above, and any loaded prefetched
225
- // models do not have loading or model states, this should have no practical effect
226
- if (resourcesToUpdate.length) {
227
- if (prevPropsRef.current) {
228
- resourcesToUpdate.forEach(([name, config]) => {
229
- var prevConfig = findConfig([name, config], getResources, prevPropsRef.current),
230
- prevCacheKey = getCacheKey(prevConfig);
231
-
232
- // unregister component from previous models that are getting updated
233
- ModelCache.unregister(componentRef.current, prevCacheKey);
234
-
235
- // this is our re-caching: if we already have a new model in the cache that has now been
236
- // saved (and thus has a real cache key), move the model to the new cache key and remove
237
- // it from the old one. this will save an unnecessary request.
238
- if (prevConfig.data && !prevConfig.data?.id && config.data?.id) {
239
- ModelCache.put(getCacheKey(config), ModelCache.get(prevCacheKey));
240
- ModelCache.remove(prevCacheKey);
241
- }
242
- });
243
- }
244
-
245
- fetchResources(resourcesToFetch, props, {
246
- component: componentRef.current,
247
- isCurrentResource: ([name, config], cacheKey) => isMountedRef.current && !config.prefetch &&
248
- cacheKey === findCacheKey([name, config], getResources, currentPropsRef.current),
249
- setResourceState,
250
- onRequestSuccess: (model, status, [name, config]) => {
251
- // to batch these state updates into one, per this comment:
252
- // https://stackoverflow.com/questions/48563650/
253
- // does-react-keep-the-order-for-state-updates/48610973#48610973
254
- ReactDOM.unstable_batchedUpdates(() => {
255
- setModels(modelAggregator([[name, config]]));
256
-
257
- loaderDispatch({
258
- type: LoadingStates.LOADED,
259
- payload: {name, config, status, resources}
260
- });
261
- });
262
- },
263
- onRequestFailure: (status, [name, config]) => {
264
- ReactDOM.unstable_batchedUpdates(() => {
265
- // request failed, which means this model should not be in the cache. but we still want
266
- // to // set our model state so that when we go back into a loading state, the empty
267
- // model is present instead of any previously-loaded model
268
- setModels(modelAggregator([[name, config]]));
269
-
270
- loaderDispatch({
271
- type: LoadingStates.ERROR,
272
- payload: {name, config, status}
273
- });
274
- });
275
- }
276
- }).then(() => {
277
- if (isMountedRef.current) {
278
- attachModelListeners();
279
- }
280
- });
281
- }
282
-
283
- prevPropsRef.current = props;
284
- // now we can reset this value
285
- cachedModelsSinceLastEffect.current = {};
286
- });
287
-
288
- // this effect attaches listeners to any bypassed models (ie, those passed in) which don't get
289
- // attached after a fetch call. additionally, the cleanup function unregisters the component from
290
- // all models and removes model listeners from all resources when unmounting
291
- useEffect(() => {
292
- var bypassedModels = resources.filter(shouldBypassFetch.bind(null, props))
293
- .map(([name, {modelKey}]) => props[getResourcePropertyName(name, modelKey)])
294
- .filter(Boolean);
295
-
296
- bypassedModels.forEach((model) => model.onUpdate(forceUpdate, componentRef.current));
297
-
298
- return () => {
299
- ModelCache.unregister(componentRef.current);
300
- // use _current_ props when getting the models here, because if any have changed over the
301
- // lifecycle of the component then they should have already had listeners removed. this only
302
- // removes listeners from the 'last' batch before unmounting
303
- resources.map(([, config]) => getModelFromCache(config))
304
- .filter(Boolean)
305
- .concat(bypassedModels)
306
- .forEach((model) => model.offUpdate(componentRef.current));
307
- };
308
- }, []);
309
-
310
- /**
311
- * This effect promptly removes any entries placed in the `refetches` resources state array.
312
- * Doing this here ensures that we don't have repeated effects with refetches, since that passes
313
- * them through the `resourcesToUpdate` path.
314
- */
315
- useEffect(() => {
316
- if ((props.refetches || []).length) {
317
- setResourceState(({refetches, ...state}) => state);
318
- }
319
- }, [(props.refetches || []).join()]);
320
-
321
- currentPropsRef.current = props;
322
-
323
- return {
324
- ...models,
325
-
326
- // spread url params and merge with state. url should take priority
327
- // over passed props (like defaultProps), but state should take
328
- // precedence over all
329
- ...props,
330
- ...props[ResourcesConfig.queryParamsPropName] || {},
331
- ...resourceState,
332
-
333
- refetch: (fn) => {
334
- var refetches = fn(ResourceKeys);
335
-
336
- if (refetches.length) {
337
- setResourceState((state) => ({...state, refetches}));
338
- }
339
- },
340
-
341
- setResourceState,
342
-
343
- // here we include our model loading states, useful for noncritical resources
344
- ...loadingStates,
345
- ...requestStatuses,
346
-
347
- // these props represent our critical resource loading states
348
- hasErrored: hasErrored(criticalLoadingStates),
349
- hasLoaded: hasLoaded(criticalLoadingStates),
350
- isLoading: isLoading(criticalLoadingStates),
351
- /**
352
- * Whether our critical resources have been loaded a first time. Useful for showing
353
- * reflecting a different UI for subsequent requests
354
- */
355
- hasInitiallyLoaded
356
- };
357
- };
358
-
359
- /**
360
- * HOC version of useResources, returning all of the same props otherwise returned by the hook. See
361
- * the comment above useResources for details on the getResources executor function, or check the
362
- * README.
363
- */
364
- export const withResources = (getResources) => (Component) =>
365
- function DataCarrier(props) {
366
- var resources = useResources(getResources, props);
367
-
368
- return (
369
- React.createElement(ErrorBoundary, {
370
- children: React.createElement(Component, {
371
- ...props,
372
- ...resources
373
- })
374
- })
375
- );
376
- };
377
-
378
- /**
379
- * Helper method to flatten the hash of resources returned by the `getResources`
380
- * function into a single array of [name, config] entries. Resource values are
381
- * objects that may also contain a `prefetches` property containing a list of
382
- * additional `props` configurations used to prefetch that resource; those are
383
- * given a `prefetch` property set to those changed props. Finally, each
384
- * resource is given a `modelKey` property equal to its ResourceKey name if not
385
- * passed in directly. `modelKey` is then used for all things fetch- and cache-
386
- * related, while `name` is used for model, loading state, and status props. If
387
- * no `modelKey` property is passed in, then it is identical to the resource's
388
- * `name`.
389
- *
390
- * @param {function} getResources - resources executor fn
391
- * @param {object} props - current component props
392
- * @return {[string, object][]} flattened [name, config] list of resources
393
- * to be consumed by the useResources with prefetch properties assigned.
394
- */
395
- function generateResources(getResources, props) {
396
- return Object.entries(getResources(ResourceKeys, props) || {})
397
- .reduce((memo, [name, config={}]) =>
398
- memo.concat([[name, {
399
- modelKey: config.modelKey || name,
400
- refetch: props.refetches?.includes(name),
401
- ...config
402
- }]].concat(
403
- // expand prefetched resources with their own options based on
404
- // their prefetch props, and store those in the `prefetch` property
405
- (config.prefetches || []).map((prefetch) => ([name, {
406
- modelKey: config.modelKey || name,
407
- ...getResources(ResourceKeys, {...props, ...prefetch})[name],
408
- prefetch
409
- }]))
410
- )), []);
411
- }
412
-
413
- /**
414
- * @param {string} name - string name of the resource
415
- * @return {string} name of the loading state property
416
- */
417
- function getResourceState(name) {
418
- return `${name}LoadingState`;
419
- }
420
-
421
- /**
422
- * @param {string} name - string name of the resource
423
- * @return {string} name of the status property
424
- */
425
- function getResourceStatus(name) {
426
- return `${name}Status`;
427
- }
428
-
429
- /**
430
- * Formulates the name of the resource prop passed to the child component, ie
431
- * this.props.todosCollection and this.props.todoItemModel.
432
- *
433
- * @param {string} baseName - string name of the resource
434
- * @param {ResourceKeys} modelKey - if the resource is not given a custom name,
435
- * this is the same as `baseName`
436
- * @return {string} name of the resource prop passed to the child component
437
- */
438
- function getResourcePropertyName(baseName, modelKey) {
439
- var Constructor = ModelMap[modelKey];
440
-
441
- return Constructor.prototype instanceof Collection ? `${baseName}Collection` :
442
- `${baseName}Model`;
443
- }
444
-
445
- /**
446
- * When a resource is not found in the ModelCache, resourcerer returns a
447
- * default empty resource so that clients can assume the model is defined
448
- * without needing to be defensive. This method freezes an empty instance of
449
- * the model associated with the modelKey and returns it.
450
- *
451
- * We seed the empty model with any attributes or models it intends on having
452
- * just in case this is a model given an `options.fetch` of `false`, in which
453
- * case we expect that the model should not have a loading state and should
454
- * appear as expected immediately.
455
- *
456
- * @param {string} config - resource config object
457
- * @return {Model|Collection} empty model or collection instance with frozen
458
- * atributes or models, respectively
459
- */
460
- function getEmptyModel({modelKey, data, options}) {
461
- var Model_ = typeof ModelMap[modelKey] === 'function' ? ModelMap[modelKey] : Model,
462
- emptyInstance = new Model_(data, options);
463
-
464
- // flag to differentiate between other model instances that happen to be empty
465
- emptyInstance.isEmptyModel = true;
466
-
467
- // ensure that no resourcerer client can modify empty model's data
468
- Object.freeze(emptyInstance.attributes);
469
- Object.freeze(emptyInstance.models);
470
-
471
- return emptyInstance;
472
- }
473
-
474
- /**
475
- * Calculates a cache key for the resource depending on the base resource type
476
- * key and the truthy parameter values. Parameter values are calculated in via
477
- * the constructor's static `dependencies` array:
478
- *
479
- * `dependencies` values are taken directly from the config object as opposed
480
- * to props, in the following order: `options` object, `data` object,
481
- * `params` object. Field keys are included in this method, which is why it is
482
- * preferred. `dependencies` entries can be functions, too, which take the
483
- * `params` object as a parameter and return a key/value object that gets
484
- * flattened to a piece of the cache key.
485
- *
486
- * We also support the deprecated `cacheFields` instead.
487
- *
488
- * @param {object} config - resource config object (destructured)
489
- * @return {string} cache key
490
- */
491
- export function getCacheKey({modelKey, params={}, options={}, data={}}) {
492
- var toKeyValString = ([key, val]) => val ? `${key}=${val}` : '',
493
- dependencies = ModelMap[modelKey]?.dependencies?.length ?
494
- ModelMap[modelKey].dependencies :
495
- ModelMap[modelKey]?.cacheFields || [],
496
- fields = dependencies.map(
497
- (key) => typeof key === 'function' ?
498
- Object.entries(key(params)).map(toKeyValString).join('_') :
499
- toKeyValString([key, options[key] || data[key] || params[key]])
500
- ).filter((x) => x);
501
-
502
- return `${modelKey || ''}${fields.sort().join('_')}`;
503
- }
504
-
505
- /**
506
- * Finds the current config object given a set of props based on the modelKey and whether it is a
507
- * prefetched resource
508
- *
509
- * @param {[name: string, {prefetch: object}]} resource name and config tuple
510
- * @param {function} getResources - resources executor fn
511
- * @param {object} props - props with which to find the cache key for a given resource
512
- * @return {string} the resource config for the resource of name `name` and matching
513
- * prefetch, if applicable
514
- */
515
- function findConfig([name, {prefetch}], getResources, props) {
516
- var [, config={}] = generateResources(getResources, props)
517
- .find(([_name, _config={}]) => name === _name &&
518
- // cheap deep equals
519
- JSON.stringify(_config.prefetch) === JSON.stringify(prefetch)) || [];
520
-
521
- return config;
522
- }
523
-
524
- /**
525
- * Our cache key generation does not use props directly, which
526
- * makes comparing current/next resources more difficult (ie, we can't just
527
- * compare `getCacheKey(config, this.props)` and `getCacheKey(config, nextProps)`)
528
- * directly because `config` itself is determined from props. However,
529
- * disregarding prefetched resources, all resources on a component must be
530
- * unique by name (otherwise one would override the other in the
531
- * getResources() return value). So we can find the current cache key by
532
- * regenerating the config a given set of props and matching it with its name
533
- * and prefetch value.
534
- *
535
- * @param {[name: string, config: object]} resource name and config tuple
536
- * @param {function} getResources - resources executor fn
537
- * @param {object} props - props with which to find the cache key for a given resource
538
- * @return {string} the cache key for the resource of name `name` and matching
539
- * prefetch, if applicable
540
- */
541
- function findCacheKey(resource, getResources, props) {
542
- return getCacheKey(findConfig(resource, getResources, props)) || '';
543
- }
544
-
545
- /**
546
- * Builds an object of loading states for resources, so that, for example,
547
- * before a fetch or refetch, all resource states are changed to LOADING.
548
- * Resources with dependencies that are not all present are put into a
549
- * 'PENDING' state.
550
- *
551
- * @param {array[]} resources - list of resource config entries for fetching
552
- * @param {object} props - current component props
553
- * @param {LoadingStates} defaultState - state to return if resource already exists in cache;
554
- * in most circumstances, this should be the LOADED state as you might expect. However, when we
555
- * prep resources to be re-fetched, they should get put into a loading state. Because we use
556
- * render bailouts to immediately update our loading states, a cached resource that no longer has
557
- * its dependent props will go back to a PENDING state, but that could be just momentarily if the
558
- * dependent prop gets added in a bailout, triggering an immediate re-render phase with no
559
- * painting to screen. Lazy models should always be considered LOADED.
560
- * @return {object} state object with resource state keys as keys and the loading
561
- * state as values
562
- */
563
- function buildResourcesLoadingState(resources, props, defaultState=LoadingStates.LOADED) {
564
- return resources.reduce((state, [name, config]) => Object.assign(state, {
565
- [getResourceState(name)]: !config.refetch && !config.force &&
566
- (shouldBypassFetch(props, [name, config]) ||
567
- (getModelFromCache(config) && !getModelFromCache(config).lazy)) ?
568
- defaultState :
569
- (!hasAllDependencies(props, [, config]) ? LoadingStates.PENDING : config.lazy ?
570
- // any lazy resource should be considered loaded in its resource state, even
571
- // though it will temporarily show up in the resourcesToUpdate list
572
- LoadingStates.LOADED :
573
- LoadingStates.LOADING)
574
- }), {});
575
- }
576
-
577
- /**
578
- * Determines whether a resource's required props for fetching are all present.
579
- *
580
- * @param {object} props - current component props
581
- * @param {{dependsOn: string|object}} resource config entry
582
- * @return {boolean} whether or not all required props are present
583
- */
584
- function hasAllDependencies(props, [, {dependsOn}]) {
585
- return !dependsOn || !dependsOn.filter((dep) => !props[dep]).length;
586
- }
587
-
588
- /**
589
- * Convenience wrapper method for getting a model from the cache. Has the same
590
- * function signature as `getCacheKey`. ModelCache will return undefined if it
591
- * doesn't find a model at the given key.
592
- *
593
- * @param {string} baseKey - model resource type key
594
- * @param {string[]|object[]} fields - list of property names whose values determine
595
- * which flavor of resource is requested
596
- * @param {object} props - current component props
597
- * @return {Model|Collection?} model from the cache
598
- */
599
- function getModelFromCache(...args) {
600
- return ModelCache.get(getCacheKey(...args));
601
- }
602
-
603
- /**
604
- * Filter predicate to remove prefetched resources from a resources list.
605
- *
606
- * @param {[, object]} config - resources config entry
607
- * @return {boolean} true if a resource is not prefetched
608
- */
609
- function withoutPrefetch([, config]) {
610
- return !config.prefetch;
611
- }
612
-
613
- /**
614
- * Filter predicate to remove noncritical resources from a resources list.
615
- *
616
- * @param {[, object]} config - resources config entry
617
- * @return {boolean} true if a resource is critical
618
- */
619
- function withoutNoncritical([, config]) {
620
- return !config.noncritical;
621
- }
622
-
623
- /**
624
- * Filter predicate to remove forced resources from a resources list.
625
- *
626
- * @param {[, object]} config - resources config entry
627
- * @return {boolean} true if a resource is not forced
628
- */
629
- function withoutForced([, config]) {
630
- return !config.force;
631
- }
632
-
633
- /**
634
- * This method determines if props with the resource names have been
635
- * passed to the component directly, in which case we'll skip the
636
- * fetching.
637
- *
638
- * @param {object} props - current component props
639
- * @param {array[]} resources - list of resource config entries for fetching
640
- * @return {boolean} whether the component should make the fetch calls
641
- */
642
- function shouldBypassFetch(props, [name, {modelKey}]) {
643
- return props.hasOwnProperty(getResourcePropertyName(name, modelKey));
644
- }
645
-
646
- /**
647
- * Negates the return value of an input function
648
- *
649
- * @param {function} fn - input function to negate
650
- * @return {function} a function that negates the return value of the input function
651
- */
652
- function not(fn) {
653
- return (...args) => !fn(...args);
654
- }
655
-
656
- /**
657
- * Hook to force a component update for a functional component by assigning a
658
- * new blank object reference every time.
659
- *
660
- * @return {function} function that, on every invocation, sets a new object as
661
- * state and causes a re-render.
662
- */
663
- function useForceUpdate() {
664
- var [, forceUpdate] = useState({});
665
-
666
- return () => forceUpdate({});
667
- }
668
-
669
- /**
670
- * @return {ref} ref whose current value is a boolean, whether or not a
671
- * component is currently mounted
672
- */
673
- function useIsMounted() {
674
- var isMountedRef = useRef(false);
675
-
676
- useEffect(() => {
677
- isMountedRef.current = true;
678
-
679
- return () => {
680
- isMountedRef.current = false;
681
- };
682
- }, []);
683
-
684
- return isMountedRef;
685
- }
686
-
687
- /**
688
- * Measures the duration of the request and calls the `track` config method
689
- * before clearing the performance markers.
690
- *
691
- * @param {string} name - resource name
692
- * @param {object<params: object, options: object>} fetch params and props
693
- */
694
- function trackRequestTime(name, {params, options}) {
695
- var measurementName = `${name}Fetch`,
696
- fetchEntry;
697
-
698
- // ensure that another resource request hasn't removed the perf mark
699
- if (window.performance.getEntriesByName(name).length) {
700
- window.performance.measure(measurementName, name);
701
- fetchEntry = window.performance.getEntriesByName(measurementName).pop();
702
-
703
- ResourcesConfig.track('API Fetch', {
704
- Resource: name,
705
- params,
706
- options,
707
- duration: Math.round(fetchEntry.duration)
708
- });
709
-
710
- window.performance.clearMarks(name);
711
- window.performance.clearMeasures(measurementName);
712
- }
713
- }
714
-
715
- /**
716
- * Dynamically gathers a list of loading states for the component's critical
717
- * resources so that we can pass down the correct values for the hasLoaded,
718
- * isLoading, and hasErrored props.
719
- *
720
- * @param {array[]} resources - list of resource config entries for fetching
721
- * @return {string[]} a list of critical loading states for the component
722
- */
723
- function getCriticalLoadingStates(loadingStates, resources) {
724
- return resources.filter(withoutNoncritical)
725
- .filter(withoutPrefetch)
726
- .map(([name]) => loadingStates[getResourceState(name)]);
727
- }
728
-
729
- /**
730
- * Helper method whose return function aggregates all models to be set as model
731
- * state in the useResources hook. Pulls model from the cache or assigns the
732
- * empty model if one does not exist. If no models have actually changed from
733
- * current state, we don't set a new object as state to avoid rerendering.
734
- *
735
- * @param {array[]} resources - list of resource config entries
736
- * @return {function} function that can be passed to a state-setting function
737
- * that returns models keyed by name
738
- */
739
- function modelAggregator(resources) {
740
- var newModels = resources.reduce((memo, [name, config]) => Object.assign(memo, {
741
- [getResourcePropertyName(name, config.modelKey)]: getModelFromCache(config) ||
742
- getEmptyModel(config)
743
- }), {});
744
-
745
- return (models={}) => Object.keys(newModels).filter(
746
- // this comparison is so that if no models have changed, we don't change state and rerender.
747
- // this is only important when a model is cached when a component mounts, because it will still
748
- // be included in resourcesToUpdate even though its model will be seeded in state already
749
- (key) => models[key] !== newModels[key]
750
- ).length ? {...models, ...newModels} : models;
751
- }
752
-
753
- /**
754
- * Separates out resources between those that are loading and those that have loaded. The latter
755
- * won't need to get passed to fetchResources, but the former will. Make sure that prefetched,
756
- * refetched, and lazy resources get added to those that are loading so that the request gets made.
757
- * Since prefetched models don't factor into loading states, there's no concern that they get passed
758
- * to fetchResources even if they have been cached.
759
- *
760
- * @param {array[]} resourcesToUpdate - resource configs to partition
761
- * @param {object} loadingStates - contains upcoming loading states for each resource
762
- * @return {[array[], array[]]} partitioned tuple of resources that have been loaded and resources
763
- * that should be passed to fetchResources
764
- */
765
- function partitionResources(resourcesToUpdate, loadingStates) {
766
- return resourcesToUpdate.reduce((memo, [name, config]) =>
767
- config.refetch || config.force || config.prefetch ||
768
- !hasLoaded(loadingStates[getResourceState(name)]) || getModelFromCache(config)?.lazy ?
769
- [memo[0], memo[1].concat([[name, config]])] :
770
- [memo[0].concat([[name, config]]), memo[1]],
771
- [[], []]);
772
- }
773
-
774
- /**
775
- * Reducer used in useResources for managing model loading states. Also includes
776
- * request status state (as in the loadingStates state object, requestStatuses
777
- * are keyed by the model name) since those are often set together (when
778
- * requests succeed or fail). Action types for this reducer are any of the
779
- * LoadingStates values: ERROR and LOADED are roughly identical, whereas
780
- * LOADING actually encompasses both LOADING and PENDING and is the only time
781
- * that we just pass loading states in directly to be set (a combination of
782
- * LOADING and PENDING).
783
- *
784
- * Also sets the hasInitiallyLoaded state when all critical loading states have
785
- * loaded for the first time.
786
- *
787
- * @param {{loadingStates: object, requestStatuses: object, hasInitiallyLoaded: boolean}} -
788
- * current loader state
789
- * @param {{type: LoadingStates, payload: object}} - reducer action object
790
- * @return {{loadingStates: object, requestStatuses: object, hasInitiallyLoaded: boolean}} -
791
- * next loader state
792
- */
793
- function loaderReducer(
794
- {loadingStates, requestStatuses, hasInitiallyLoaded},
795
- {type, payload={}}
796
- ) {
797
- var {name, status, resources} = payload;
798
-
799
- switch (type) {
800
- case LoadingStates.ERROR:
801
- case LoadingStates.LOADED: {
802
- let nextLoadingStates = {...loadingStates, [getResourceState(name)]: type};
803
-
804
- return {
805
- loadingStates: nextLoadingStates,
806
- requestStatuses: {...requestStatuses, [getResourceStatus(name)]: status},
807
- hasInitiallyLoaded: hasInitiallyLoaded || (type === LoadingStates.LOADED &&
808
- hasLoaded(getCriticalLoadingStates(nextLoadingStates, resources)) && !hasInitiallyLoaded)
809
- };
810
- }
811
- case LoadingStates.LOADING:
812
- return {
813
- loadingStates: {...loadingStates, ...payload},
814
- requestStatuses,
815
- hasInitiallyLoaded
816
- };
817
- default:
818
- return {loadingStates, requestStatuses, hasInitiallyLoaded};
819
- }
820
- }
821
-
822
- /**
823
- * Whether to measure a particular request time, based on a static `measure` property
824
- * on the model itself (and not the request). `measure` can be a boolean, which if true
825
- * will track all requests for this model, or a function that takes its resource config
826
- * object to only track requests that meet a specific condition.
827
- *
828
- * @param {ResourceKeys} modelKey - key representing model to be measured
829
- * @param {object} config - resource config object for a particular request instance
830
- * @return {boolean} whether a particular request time should be measured
831
- */
832
- function shouldMeasureRequest(modelKey, config) {
833
- if (!window.performance || !window.performance.mark) {
834
- return false;
835
- }
836
-
837
- return typeof ModelMap[modelKey].measure === 'function' ?
838
- ModelMap[modelKey].measure(config) :
839
- !!ModelMap[modelKey].measure;
840
- }
841
-
842
- /**
843
- * Here's where we do the fetching for a given set of resources. We combine the
844
- * promises into a single Promise.all so that we wait until all fetches complete
845
- * before listening on them. Note that Promise.all takes the promise returned
846
- * from the fetch's catch method, so that even if a request fails, Promise.all
847
- * will not reject.
848
- *
849
- * @param {array[]} resources - list of resource config entries for fetching
850
- * @param {object} props - current component props
851
- * @param {object} options - object whose properties allow us to shim any
852
- * differences between the withResources HOC and the useResources hook.
853
- * contains properties:
854
- * component {object} - reference to the component instance, or in the case of
855
- * function components, a unique and consistent object reference to associate
856
- * with the component instance.
857
- * isCurrentResource {function} - should true if a returned resource is the
858
- * current resource for a component instance (ie, no newer requests were
859
- * made in the interim)
860
- * setResourceState {function} - updates resource state
861
- * onRequestSuccess {function} - called after a request succeeds
862
- * onRequestFailure {function} - called after a request fails
863
- */
864
- function fetchResources(resources, props, {
865
- component,
866
- isCurrentResource,
867
- setResourceState,
868
- onRequestSuccess,
869
- onRequestFailure
870
- }) {
871
- // ensure critical requests go out first
872
- /* eslint-disable id-length */
873
- resources = resources.concat().sort((a, b) =>
874
- a[1].prefetch ? 2 : b[1].prefetch ? -2 : a[1].noncritical ? 1 : b[1].noncritical ? -1 : 0);
875
- /* eslint-enable id-length */
876
-
877
- return Promise.all(
878
- // nice visual for this promise chain: http://tinyurl.com/y6wt47b6
879
- resources.map(([name, config]) => {
880
- var {params, modelKey, provides={}, refetch, ...rest} = config,
881
- cacheKey = getCacheKey(config),
882
- shouldMeasure = shouldMeasureRequest(modelKey, config) && !getModelFromCache(config);
883
-
884
- if (shouldMeasure) {
885
- window.performance.mark(name);
886
- }
887
-
888
- return request(cacheKey, ModelMap[modelKey], {
889
- fetch: !UnfetchedResources.has(modelKey),
890
- params,
891
- component,
892
- force: refetch,
893
- ...rest
894
- }).then(
895
- // success callback, where we track request time and add any dependent props or models
896
- ([model, status]) => {
897
- if (shouldMeasure) {
898
- trackRequestTime(name, config);
899
- }
900
-
901
- // add unfetched resources that a model might provide
902
- if (ModelMap[modelKey].providesModels) {
903
- ModelMap[modelKey].providesModels(model, ResourceKeys).forEach((uConfig) => {
904
- var uCacheKey = getCacheKey(uConfig),
905
- existingModel = ModelCache.get(uCacheKey);
906
-
907
- if (typeof uConfig.shouldCache !== 'function' ||
908
- uConfig.shouldCache(existingModel, uConfig)) {
909
- // components may be listening to existing models, so only create
910
- // new model if one does not currently exist
911
- existingModel ?
912
- existingModel.set(uConfig.data) :
913
- ModelCache.put(
914
- uCacheKey,
915
- new ModelMap[uConfig.modelKey](uConfig.data, uConfig.options),
916
- component
917
- );
918
- }
919
- });
920
- }
921
-
922
- // don't continue unless component is still mounted and resource is current
923
- if (isCurrentResource([name, config], cacheKey)) {
924
- // add any dependencies this resource might provide for other resources
925
- provideProps(model, provides, props, setResourceState);
926
- onRequestSuccess(model, status, [name, config]);
927
- }
928
- },
929
-
930
- // error callback
931
- (status) => {
932
- // this catch block gets called _only_ for request errors.
933
- // don't set error state unless resource is current
934
- if (isCurrentResource([name, config], cacheKey)) {
935
- onRequestFailure(status, [name, config]);
936
- }
937
- }
938
- );
939
- })
940
- );
941
- }
942
-
943
- /**
944
- * Add any dependencies that the model provides as resource state.
945
- *
946
- * @param {Model|Collection} model
947
- * @param {object} provides - config provides object
948
- * @param {object} props - current component props
949
- * @param {function} setResourceState - updates resource state
950
- */
951
- function provideProps(model, provides={}, props, setResourceState) {
952
- if (Object.entries(provides).length) {
953
- setResourceState((state) => ({
954
- ...state,
955
- ...Object.entries(provides).reduce((memo, [provide, transform]) => Object.assign({
956
- memo,
957
- ...(provide === SPREAD_PROVIDES_CHAR ?
958
- transform(model, props) :
959
- {[provide]: transform(model, props)})
960
- }), {})
961
- }));
962
- }
963
- }