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