resourcerer 1.0.0-alpha-3 → 1.0.0-beta-4

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.
@@ -1,6 +1,8 @@
1
- import {hasErrored, hasLoaded, isLoading, pick} from './utils';
1
+ import {hasErrored, hasLoaded, isLoading} from './utils';
2
2
  import {ModelMap, ResourceKeys, ResourcesConfig, UnfetchedResources} from './config';
3
+ /* eslint-disable no-unused-vars */
3
4
  import React, {useEffect, useReducer, useRef, useState} from 'react';
5
+ /* eslint-enable no-unused-vars */
4
6
 
5
7
  import Collection from './collection';
6
8
  import ErrorBoundary from './error-boundary';
@@ -13,52 +15,13 @@ import request from './request';
13
15
  const SPREAD_PROVIDES_CHAR = '_';
14
16
 
15
17
  /**
16
- * This HOC is a light wrapper around the DataCarrier component for setting
17
- * state that should trigger resource updates. Some things won't need this, ie
18
- * a url update that passes its query params down as props[queryParamsPropName].
19
- * But it provides a setResourceState method to wrap any necessary state that
20
- * may cause a resource update in DataCarrier's componentDidUpdate.
21
- */
22
- const resourceState = (Component) =>
23
- class ResourceStateWrapper extends React.Component {
24
- constructor() {
25
- super();
26
- this.state = {};
27
- }
28
-
29
- setResourceState(newState={}, cb) {
30
- this.setState(
31
- typeof newState === 'function' ? (state) => newState(state) : {
32
- ...this.state,
33
- ...newState
34
- },
35
- cb
36
- );
37
- }
38
-
39
- render() {
40
- return (
41
- <Component
42
- {...this.props}
43
- // spread url params and merge with state. url should take priority
44
- // over passed props (like defaultProps), but state should take
45
- // precedence over all
46
- {...this.props[ResourcesConfig.queryParamsPropName] || {}}
47
- {...this.state}
48
- setResourceState={this.setResourceState.bind(this)}
49
- />
50
- );
51
- }
52
- };
53
-
54
- /**
55
- * The withResources decorator produces a Data Carrier component that handles
56
- * several different data-related things for a component automatically:
18
+ * The useResources hook handles several different data-related things for a component
19
+ * automatically:
57
20
  *
58
- * 1. it fetches a component's resources in cDM
21
+ * 1. it fetches a component's resources after mounting
59
22
  * 2. it binds listeners to all resources
60
23
  * 3. it handles whether or not the critical resources for a component have loaded
61
- * 4. it re-fetches a new resource in cDU when specified props have changed
24
+ * 4. it re-fetches a new resource when specified props have changed
62
25
  * 5. it handles resource cache naming for the ModelCache
63
26
  *
64
27
  * getResources is a function that takes props as an argument and should return
@@ -70,8 +33,8 @@ const resourceState = (Component) =>
70
33
  * * noncritical {boolean} - whether the resource should not be taken into
71
34
  * account when determining the loading state of the component. default
72
35
  * is false
73
- * * data {object} - data for the fetch call passed to the `request`
74
- * * options {object} - options object passed to the model's `initialize`
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)
75
38
  * * dependsOn {string[]} - prop fields required to be present before the
76
39
  * resource will fetch
77
40
  * * provides {object<string: function>[]} - list of props that a resource
@@ -81,8 +44,6 @@ const resourceState = (Component) =>
81
44
  * a value to be set for the prop. If the key is equal to
82
45
  * SPREAD_PROVIDES_CHAR, then the return value of the transform function
83
46
  * is spread for dynamically-provided props.
84
- * * status {boolean} - whether the component requires the status of the http
85
- * request to be passed along.
86
47
  * * prefetch {object} - an individual map of expected future props to fetch
87
48
  * a new resource and store it in the cache. it will not, however, get
88
49
  * passed down to the child (no loading states, either)
@@ -94,290 +55,9 @@ const resourceState = (Component) =>
94
55
  * fetched and cached
95
56
  * * ...any other option that can be passed directly to the `request` function
96
57
  */
97
- export const withResources = (getResources) =>
98
- (Component) => {
99
- @resourceState
100
- class DataCarrier extends React.Component {
101
- constructor(props) {
102
- super();
103
-
104
- let resources = this._generateResources(props);
105
- let initialLoadingStates = buildResourcesLoadingState(
106
- resources.filter(withoutPrefetch),
107
- props
108
- );
109
-
110
- this.prevPropsRef = React.createRef({});
111
-
112
- // set initial loading state for our resources
113
- this.state = {
114
- // our models kept as state. in the past they were not, and they were only read directly
115
- // from the cache. this works and is super clean, but a big downside is that there is a
116
- // lot you have to juggle to show a model based on prevProps when props have changed.
117
- // this is ultimately just simpler, despite the denormalization
118
- ...resources.filter(withoutPrefetch).reduce((models, [name, config]) => ({
119
- ...models,
120
- [getResourcePropertyName(name, config.modelKey)]: getModelFromCache(config) ||
121
- getEmptyModel(config)
122
- }), {}),
123
- ...initialLoadingStates,
124
- /**
125
- * Whether our critical resources have been loaded a first time. Useful for showing
126
- * reflecting a different UI for subsequent requests
127
- */
128
- hasInitiallyLoaded: hasLoaded(getCriticalLoadingStates(initialLoadingStates, resources))
129
- };
130
- }
131
-
132
- componentDidMount() {
133
- var resources = this._generateResources()
134
- .filter(hasAllDependencies.bind(null, this.props))
135
- .filter(not(shouldBypassFetch.bind(null, this.props)));
136
-
137
- // fetch models
138
- this._fetchResources(resources);
139
- this._isMounted = true;
140
-
141
- this._attachModelListeners();
142
- }
143
-
144
- componentDidUpdate(prevProps) {
145
- // update models based on new props or new resources
146
- var nextResources = this._generateResources(),
147
- pendingResources = nextResources.filter(not(hasAllDependencies.bind(null, this.props)))
148
- .filter(([, config]) => hasAllDependencies(prevProps, [, config])),
149
- resourcesToUpdate = this._getResourcesToUpdate(nextResources, prevProps),
150
- nextLoadingStates = {
151
- ...buildResourcesLoadingState(pendingResources, this.props, LoadingStates.PENDING),
152
- // but resourcesToUpdate should get set to LOADING (or LOADED if in the cache)
153
- ...buildResourcesLoadingState(resourcesToUpdate.filter(withoutPrefetch), this.props)
154
- },
155
-
156
- // separate out those resources to update into those that are already cached and those
157
- // that need to be fetched. the former will get the models updated immediately
158
- [loadedResources, resourcesToFetch] = partitionResources(
159
- resourcesToUpdate,
160
- nextLoadingStates
161
- );
162
-
163
- // first set our updated resources' loading states to LOADING. also, any
164
- // resources that have lost their dependencies should go back to a pending state
165
- // and their models reverted to the empty models. new resources that have already
166
- // been loaded should be set to LOADED with their cached models set as state immediately
167
- if (pendingResources.length || resourcesToUpdate.length) {
168
- this.setState({
169
- ...pendingResources.concat(loadedResources).filter(withoutPrefetch)
170
- .reduce((memo, [name, config]) => Object.assign(memo, {
171
- // if pending resource cache key doesn't change, don't reset it to empty
172
- [getResourcePropertyName(name, config.modelKey)]: getModelFromCache(config) ||
173
- getEmptyModel(config)
174
- }), {}),
175
- ...nextLoadingStates
176
- });
177
- }
178
-
179
- resourcesToFetch.forEach(([name, config]) => {
180
- var previousConfig = findConfig([name, config], getResources, prevProps),
181
- previousCacheKey = this._findCurrentCacheKey([name, config], prevProps);
182
-
183
- // unregister component from previous models that are getting updated
184
- ModelCache.unregister(this, previousCacheKey);
185
-
186
- // this is our re-caching: if we already have a new model in the cache that has now been
187
- // saved (and thus has a real cache key), move the model to the new cache key and remove
188
- // it from the old one. this will save an unnecessary request.
189
- if (previousConfig.attributes && !previousConfig.attributes.id && config.attributes?.id) {
190
- ModelCache.put(getCacheKey(config), ModelCache.get(previousCacheKey));
191
- ModelCache.remove(previousCacheKey);
192
- }
193
- });
194
-
195
- if (resourcesToFetch.length) {
196
- this._fetchResources(resourcesToFetch);
197
- }
198
-
199
- if ((this.props.refetches || []).length) {
200
- this.props.setResourceState((state) => ({...state, refetches: []}));
201
- }
202
-
203
- this.prevPropsRef.current = this.props;
204
- }
205
-
206
- componentWillUnmount() {
207
- this._isMounted = false;
208
- this._unattachModelListeners.call(this);
209
- ModelCache.unregister(this);
210
- }
211
-
212
- _fetchResources(resources, props=this.props) {
213
- return fetchResources(resources, props, {
214
- component: this,
215
- isCurrentResource: ([name, config], cacheKey) => this._isMounted && !config.prefetch &&
216
- cacheKey === this._findCurrentCacheKey([name, config]),
217
- setResourceState: props.setResourceState,
218
- onRequestSuccess: (model, status, [name, config]) => {
219
- // set loading state _after_ all its dependencies are added
220
- this.setState((state) => {
221
- var nextState = {
222
- ...state,
223
- [getResourceState(name)]: LoadingStates.LOADED,
224
- [getResourcePropertyName(name, config.modelKey)]: model,
225
- ...(config.status ? {[getResourceStatus(name)]: status} : {})
226
- };
227
-
228
- return {
229
- ...nextState,
230
- // if we haven't already loaded and this response gets us into the loaded state
231
- // across our critical resources, set the hasInitiallyLoaded flag
232
- ...!this.state.hasInitiallyLoaded &&
233
- hasLoaded(getCriticalLoadingStates(nextState, resources)) ?
234
- {hasInitiallyLoaded: true} : {}
235
- };
236
- });
237
- },
238
- onRequestFailure: (status, [name, config]) => {
239
- // this catch block gets called _only_ for request errors
240
- this.setState({
241
- [getResourceState(name)]: LoadingStates.ERROR,
242
- ...(config.status ? {[getResourceStatus(name)]: status} : {})
243
- });
244
- }
245
- }).then(() => {
246
- if (this._isMounted) {
247
- // attaches listeners on all resources (removes any existing first)
248
- this._attachModelListeners();
249
- }
250
- });
251
- }
252
-
253
- _getResourcesToUpdate(resources, prevProps) {
254
- return resources.filter(hasAllDependencies.bind(null, this.props))
255
- .filter(not(shouldBypassFetch.bind(null, this.props)))
256
- .filter(([name, config]) =>
257
- this._hasResourceConfigChanged(name, config, prevProps) ||
258
- !hasAllDependencies(prevProps, [, config]) || config.refetch);
259
- }
260
-
261
- _generateResources(props=this.props) {
262
- return generateResources(getResources, props);
263
- }
264
-
265
- _findCurrentCacheKey(resource, props=this.props) {
266
- return findCacheKey(resource, getResources, props);
267
- }
268
-
269
- /**
270
- * This method determines whether a resource's config has changed between
271
- * this.props and prevProps. We compare cache key strings for this.props/prevProps
272
- *
273
- * @param {string} name - resource name
274
- * @param {object} config - resource config object
275
- * @param {object} prevProps - component's prevProps, used to compare
276
- * cache keys with current props
277
- * @return {boolean} whether a resource's config has changed between
278
- * this.props and prevProps, which will prompt a refetch
279
- */
280
- _hasResourceConfigChanged(name, config, prevProps) {
281
- var currentCacheKey = this._findCurrentCacheKey([name, config]),
282
- previousCacheKey = this._findCurrentCacheKey([name, config], prevProps);
283
-
284
- // currentCacheKey won't exist if the current resource is a prefetched resource,
285
- // which we don't want to consider for determining a changed config
286
- return !currentCacheKey || currentCacheKey !== previousCacheKey;
287
- }
288
-
289
- // NOTE: this must be bound here to keep React.memo working when shallow-comparing props
290
- _refetch = (fn) => {
291
- var refetches = fn(ResourceKeys);
292
-
293
- if (refetches.length) {
294
- this.props.setResourceState((state) => ({...state, refetches}));
295
- }
296
- }
297
-
298
- _onModelEvent() {
299
- this.forceUpdate();
300
- }
301
-
302
- _attachModelListeners() {
303
- var modelsToAttach = this._generateResources()
304
- .map(([, config]) => getModelFromCache(config))
305
- .filter(Boolean);
306
-
307
- // unattach any previously-attached listeners first
308
- this._unattachModelListeners();
309
-
310
- // whenever there may be a change in the data, trigger a React update.
311
- modelsToAttach.forEach((model) => model.onUpdate(
312
- this._onModelEvent,
313
- this.listeningContext || this
314
- ));
315
-
316
- this._attachedModels = modelsToAttach;
317
- }
318
-
319
- /**
320
- * Removes all model event listeners from a component. This happens automatically
321
- * on componentWillUnmount, but also before any listeners are manually attached.
322
- */
323
- _unattachModelListeners() {
324
- // Ensure that we clean up any dangling references when the component is destroyed.
325
- (this._attachedModels || []).forEach((model) => model.offUpdate(
326
- this.listeningContext || this
327
- ));
328
- this._attachedModels = null;
329
- }
330
-
331
- render() {
332
- var resources = this._generateResources().filter(withoutPrefetch),
333
- loadingStates = getCriticalLoadingStates(this.state, resources);
334
-
335
- return (
336
- <ErrorBoundary>
337
- <Component
338
- {...(Component.prototype || {}).isReactComponent ? {
339
- // allows for our listeners to call forceUpdate in this context, so that even
340
- // PureComponents get updated
341
- ref: (dataChild) => this.listeningContext = dataChild
342
- } : {}}
343
-
344
- // here we pass down our models
345
- {...pick(
346
- this.state,
347
- ...resources.map(([name, {modelKey}]) => getResourcePropertyName(name, modelKey))
348
- )}
349
-
350
- // here we include our model loading states, useful for noncritical resources
351
- {...pick(this.state, ...resources.map(([name]) => getResourceState(name)))}
352
- {...pick(this.state, ...resources.map(([name]) => getResourceStatus(name)))}
353
- {...this.props}
354
-
355
- // these props represent our critical resource loading states
356
- hasErrored={hasErrored(loadingStates)}
357
- hasInitiallyLoaded={this.state.hasInitiallyLoaded}
358
- hasLoaded={hasLoaded(loadingStates)}
359
- isLoading={isLoading(loadingStates)}
360
-
361
- // helpers
362
- refetch={this._refetch}
363
- />
364
- </ErrorBoundary>
365
- );
366
- }
367
- }
368
-
369
- return DataCarrier;
370
- };
371
-
372
- /**
373
- * Hook version of withResources, returning all of the same props otherwise
374
- * passed down in the HOC, as well as a setResourceState() fn. See the comment
375
- * above withResources for details on the getResources executor function, or
376
- * check the README.
377
- */
378
58
  export const useResources = (getResources, props) => {
379
- var [_resourceState, setResourceState] = useState({}),
380
- props = {...props, ..._resourceState},
59
+ var [resourceState, setResourceState] = useState({}),
60
+ props = {...props, ...resourceState},
381
61
  resources = generateResources(getResources, props),
382
62
 
383
63
  initialLoadingStates = buildResourcesLoadingState(resources.filter(withoutPrefetch), props),
@@ -493,7 +173,7 @@ export const useResources = (getResources, props) => {
493
173
  // this is our re-caching: if we already have a new model in the cache that has now been
494
174
  // saved (and thus has a real cache key), move the model to the new cache key and remove
495
175
  // it from the old one. this will save an unnecessary request.
496
- if (prevConfig.attributes && !prevConfig.attributes?.id && config.attributes?.id) {
176
+ if (prevConfig.data && !prevConfig.data?.id && config.data?.id) {
497
177
  ModelCache.put(getCacheKey(config), ModelCache.get(prevCacheKey));
498
178
  ModelCache.remove(prevCacheKey);
499
179
  }
@@ -588,7 +268,7 @@ export const useResources = (getResources, props) => {
588
268
  // precedence over all
589
269
  ...props,
590
270
  ...props[ResourcesConfig.queryParamsPropName] || {},
591
- ..._resourceState,
271
+ ...resourceState,
592
272
 
593
273
  // helpers
594
274
  isOrWillBeLoading: () => {
@@ -629,6 +309,22 @@ export const useResources = (getResources, props) => {
629
309
  };
630
310
  };
631
311
 
312
+ /**
313
+ * HOC version of useResources, returning all of the same props otherwise returned by the hook. See
314
+ * the comment above useResources for details on the getResources executor function, or check the
315
+ * README.
316
+ */
317
+ export const withResources = (getResources) => (Component) =>
318
+ function DataCarrier(props) {
319
+ var resources = useResources(getResources, props);
320
+
321
+ return (
322
+ <ErrorBoundary>
323
+ <Component {...props} {...resources} />
324
+ </ErrorBoundary>
325
+ );
326
+ };
327
+
632
328
  /**
633
329
  * Helper method to flatten the hash of resources returned by the `getResources`
634
330
  * function into a single array of [name, config] entries. Resource values are
@@ -644,8 +340,7 @@ export const useResources = (getResources, props) => {
644
340
  * @param {function} getResources - resources executor fn
645
341
  * @param {object} props - current component props
646
342
  * @return {[string, object][]} flattened [name, config] list of resources
647
- * to be consumed by the withResources HOC with prefetch properties
648
- * assigned.
343
+ * to be consumed by the useResources with prefetch properties assigned.
649
344
  */
650
345
  function generateResources(getResources, props) {
651
346
  return Object.entries(getResources(ResourceKeys, props) || {})
@@ -667,7 +362,7 @@ function generateResources(getResources, props) {
667
362
 
668
363
  /**
669
364
  * @param {string} name - string name of the resource
670
- * @return {string} name of the loading state property within DataCarrier state
365
+ * @return {string} name of the loading state property
671
366
  */
672
367
  function getResourceState(name) {
673
368
  return `${name}LoadingState`;
@@ -675,7 +370,7 @@ function getResourceState(name) {
675
370
 
676
371
  /**
677
372
  * @param {string} name - string name of the resource
678
- * @return {string} name of the status property within DataCarrier state
373
+ * @return {string} name of the status property
679
374
  */
680
375
  function getResourceStatus(name) {
681
376
  return `${name}Status`;
@@ -698,7 +393,7 @@ function getResourcePropertyName(baseName, modelKey) {
698
393
  }
699
394
 
700
395
  /**
701
- * When a resource is not found in the ModelCache, withResources returns a
396
+ * When a resource is not found in the ModelCache, resourcerer returns a
702
397
  * default empty resource so that clients can assume the model is defined
703
398
  * without needing to be defensive. This method freezes an empty instance of
704
399
  * the model associated with the modelKey and returns it.
@@ -712,12 +407,9 @@ function getResourcePropertyName(baseName, modelKey) {
712
407
  * @return {Model|Collection} empty model or collection instance with frozen
713
408
  * atributes or models, respectively
714
409
  */
715
- function getEmptyModel({modelKey, attributes, models, options}) {
410
+ function getEmptyModel({modelKey, data, options}) {
716
411
  var Model_ = typeof ModelMap[modelKey] === 'function' ? ModelMap[modelKey] : Model,
717
- emptyInstance = new Model_(
718
- Model_.prototype instanceof Collection ? models : attributes,
719
- options
720
- );
412
+ emptyInstance = new Model_(data, options);
721
413
 
722
414
  // flag to differentiate between other model instances that happen to be empty
723
415
  emptyInstance.isEmptyModel = true;
@@ -735,21 +427,21 @@ function getEmptyModel({modelKey, attributes, models, options}) {
735
427
  * the constructor's static `cacheFields` array:
736
428
  *
737
429
  * `cacheFields` values are taken directly from the config object as opposed
738
- * to props, in the following order: `options` object, `attributes` object,
739
- * `data` object. Field keys are included in this method, which is why it is
430
+ * to props, in the following order: `options` object, `data` object,
431
+ * `params` object. Field keys are included in this method, which is why it is
740
432
  * preferred. `cacheFields` entries can be functions, too, which take the
741
- * `data` object as a parameter and return a key/value object that gets
433
+ * `params` object as a parameter and return a key/value object that gets
742
434
  * flattened to a piece of the cache key.
743
435
  *
744
436
  * @param {object} config - resource config object (destructured)
745
437
  * @return {string} cache key
746
438
  */
747
- export function getCacheKey({modelKey, data={}, options={}, attributes={}}) {
439
+ export function getCacheKey({modelKey, params={}, options={}, data={}}) {
748
440
  var toKeyValString = ([key, val]) => val ? `${key}=${val}` : '',
749
441
  fields = (ModelMap[modelKey]?.cacheFields || []).map(
750
442
  (key) => typeof key === 'function' ?
751
- Object.entries(key(data)).map(toKeyValString).join('_') :
752
- toKeyValString([key, options[key] || attributes[key] || data[key]])
443
+ Object.entries(key(params)).map(toKeyValString).join('_') :
444
+ toKeyValString([key, options[key] || data[key] || params[key]])
753
445
  ).filter((x) => x);
754
446
 
755
447
  return `${modelKey || ''}${fields.sort().join('_')}`;
@@ -775,7 +467,7 @@ function findConfig([name, {prefetch}], getResources, props) {
775
467
  }
776
468
 
777
469
  /**
778
- * Our cache key generation no longer uses props directly, which
470
+ * Our cache key generation does not use props directly, which
779
471
  * makes comparing current/next resources more difficult (ie, we can't just
780
472
  * compare `getCacheKey(config, this.props)` and `getCacheKey(config, nextProps)`)
781
473
  * directly because `config` itself is determined from props. However,
@@ -926,9 +618,9 @@ function useIsMounted() {
926
618
  * before clearing the performance markers.
927
619
  *
928
620
  * @param {string} name - resource name
929
- * @param {object<data: object, options: object>} fetch data and options
621
+ * @param {object<params: object, options: object>} fetch params and props
930
622
  */
931
- function trackRequestTime(name, {data, options}) {
623
+ function trackRequestTime(name, {params, options}) {
932
624
  var measurementName = `${name}Fetch`,
933
625
  fetchEntry;
934
626
 
@@ -939,7 +631,7 @@ function trackRequestTime(name, {data, options}) {
939
631
 
940
632
  ResourcesConfig.track('API Fetch', {
941
633
  Resource: name,
942
- data,
634
+ params,
943
635
  options,
944
636
  duration: Math.round(fetchEntry.duration)
945
637
  });
@@ -989,7 +681,10 @@ function modelAggregator(resources) {
989
681
 
990
682
  /**
991
683
  * Separates out resources between those that are loading and those that have loaded. The latter
992
- * won't need to get passed to fetchResources, but the former will.
684
+ * won't need to get passed to fetchResources, but the former will. Make sure that prefetched
685
+ * resources get added to those that are loading so that the request gets made. Since prefetched
686
+ * models don't factor into loading states, there's no concern that they get passed to
687
+ * fetchResources even if they have been cached.
993
688
  *
994
689
  * @param {array[]} resourcesToUpdate - resource configs to partition
995
690
  * @param {object} loadingStates - contains upcoming loading states for each resource
@@ -998,7 +693,7 @@ function modelAggregator(resources) {
998
693
  */
999
694
  function partitionResources(resourcesToUpdate, loadingStates) {
1000
695
  return resourcesToUpdate.reduce((memo, [name, config]) =>
1001
- config.refetch || !hasLoaded(loadingStates[getResourceState(name)]) ?
696
+ config.refetch || config.prefetch || !hasLoaded(loadingStates[getResourceState(name)]) ?
1002
697
  [memo[0], memo[1].concat([[name, config]])] :
1003
698
  [memo[0].concat([[name, config]]), memo[1]],
1004
699
  [[], []]);
@@ -1065,11 +760,6 @@ function loaderReducer(
1065
760
  function shouldMeasureRequest(modelKey, config) {
1066
761
  if (!window.performance || !window.performance.mark) {
1067
762
  return false;
1068
- // this is legacy and undocumented, but allows measuring on an instance-basis,
1069
- // which can cause unpredictable behavior if two components request the same
1070
- // resource but only one has {measure: true} configured.
1071
- } else if (config.measure) {
1072
- return true;
1073
763
  }
1074
764
 
1075
765
  return typeof ModelMap[modelKey].measure === 'function' ?
@@ -1115,7 +805,7 @@ function fetchResources(resources, props, {
1115
805
  return Promise.all(
1116
806
  // nice visual for this promise chain: http://tinyurl.com/y6wt47b6
1117
807
  resources.map(([name, config]) => {
1118
- var {data, modelKey, provides={}, refetch, ...rest} = config,
808
+ var {params, modelKey, provides={}, refetch, ...rest} = config,
1119
809
  cacheKey = getCacheKey(config),
1120
810
  shouldMeasure = shouldMeasureRequest(modelKey, config) && !getModelFromCache(config);
1121
811
 
@@ -1125,7 +815,7 @@ function fetchResources(resources, props, {
1125
815
 
1126
816
  return request(cacheKey, ModelMap[modelKey], {
1127
817
  fetch: !UnfetchedResources.has(modelKey),
1128
- data,
818
+ params,
1129
819
  component,
1130
820
  forceFetch: refetch,
1131
821
  ...rest
@@ -1147,13 +837,10 @@ function fetchResources(resources, props, {
1147
837
  // components may be listening to existing models, so only create
1148
838
  // new model if one does not currently exist
1149
839
  existingModel ?
1150
- existingModel.set(uConfig.models || uConfig.attributes) :
840
+ existingModel.set(uConfig.data) :
1151
841
  ModelCache.put(
1152
842
  uCacheKey,
1153
- new ModelMap[uConfig.modelKey](
1154
- uConfig.models || uConfig.attributes,
1155
- uConfig.options || {}
1156
- ),
843
+ new ModelMap[uConfig.modelKey](uConfig.data, uConfig.options),
1157
844
  component
1158
845
  );
1159
846
  }
package/lib/sync.js CHANGED
@@ -8,8 +8,8 @@ var prefilter = (x) => x;
8
8
 
9
9
  /**
10
10
  * The basic sync function, which does very little other than prep the options argument sent to the
11
- * ajax function. It basically sets up defaults, seeding the query data if not explicitly specified
12
- * already. It also finds the base url or throws if one does not exist.
11
+ * ajax function. It basically sets up defaults, seeding the query params if not explicitly
12
+ * specified already. It also finds the base url or throws if one does not exist.
13
13
  *
14
14
  * @param {Model|Collection} model - model making API request
15
15
  * @param {object} options - generic map of request options
@@ -20,9 +20,9 @@ export default function(model, options={}) {
20
20
  return ajax({
21
21
  contentType: MIME_TYPE_JSON,
22
22
  // url can be passed via the model (as a property or function) or via options.url directly
23
- ...!options.url ? {url: result(model, 'url') || urlError()} : {},
24
- ...!options.data && ['POST', 'PATCH', 'PUT'].includes(options.method) ?
25
- {data: options.attrs || model.toJSON()} :
23
+ ...!options.url ? {url: result(model, 'url', model.urlOptions) || urlError()} : {},
24
+ ...!options.params && ['POST', 'PATCH', 'PUT'].includes(options.method) ?
25
+ {params: options.attrs || model.toJSON()} :
26
26
  {},
27
27
  // default catch block. most large applications should override this in the config settings to
28
28
  // provide support for things like 401s or 429s.
@@ -38,7 +38,8 @@ export default function(model, options={}) {
38
38
  * @param {object} options - map of request options:
39
39
  * * url {string} - this is required, but will be present automatically if not passed directly in
40
40
  * the sync method's request object
41
- * * data {object} - will be url-stringified for GET requests and JSON-stringified for POST bodies
41
+ * * params {object} - will be url-stringified for GET requests and JSON-stringified for POST
42
+ * bodies
42
43
  * * headers {object} - map of headers to their values
43
44
  * * contentType {string} value of content type header, which will also determine how the POST
44
45
  * bodies are assembled
@@ -48,12 +49,12 @@ export default function(model, options={}) {
48
49
  * rejects with the response
49
50
  */
50
51
  export function ajax(options) {
51
- var hasData = !!Object.keys(options.data || {}).length,
52
- hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasData;
52
+ var hasParams = !!Object.keys(options.params || {}).length,
53
+ hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasParams;
53
54
 
54
- if (options.method === 'GET' && hasData) {
55
+ if (options.method === 'GET' && hasParams) {
55
56
  options.url += (options.url.indexOf('?') > -1 ? '&' : '?') +
56
- ResourcesConfig.stringify(options.data, options);
57
+ ResourcesConfig.stringify(options.params, options);
57
58
  }
58
59
 
59
60
  options = {...options, ...prefilter(options)};
@@ -62,17 +63,17 @@ export function ajax(options) {
62
63
  ...options,
63
64
  headers: {
64
65
  Accept: MIME_TYPE_JSON,
65
- // only set contentType header if a write request and if there is body data. also, default to
66
- // JSON contentTypes, but allow for it to be overridden, ie with x-www-form-urlencoded.
66
+ // only set contentType header if a write request and if there is body params. also, default
67
+ // to JSON contentTypes, but allow for it to be overridden, ie with x-www-form-urlencoded.
67
68
  ...hasBodyContent ? {'Content-Type': options.contentType} : {},
68
69
  ...options.headers
69
70
  },
70
71
  ...hasBodyContent ? {
71
- body: typeof options.data === 'string' ?
72
- options.data :
72
+ body: typeof options.params === 'string' ?
73
+ options.params :
73
74
  options.contentType === MIME_TYPE_JSON ?
74
- JSON.stringify(options.data) :
75
- ResourcesConfig.stringify(options.data, options)
75
+ JSON.stringify(options.params) :
76
+ ResourcesConfig.stringify(options.params, options)
76
77
  } : {}
77
78
  // catch block here handles the case where the response isn't valid json,
78
79
  // like for example a 204 no content
package/lib/utils.js CHANGED
@@ -215,6 +215,6 @@ export function sortBy(list=[], comparator) {
215
215
  * @param {any} prop - property of object to evaluate
216
216
  * @return {any} evaluated value of object at property
217
217
  */
218
- export function result(obj={}, prop) {
219
- return typeof obj[prop] === 'function' ? obj[prop]() : obj[prop];
218
+ export function result(obj={}, prop, ...args) {
219
+ return typeof obj[prop] === 'function' ? obj[prop](...args) : obj[prop];
220
220
  }