resourcerer 1.0.0-beta-3 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +170 -139
- package/lib/collection.js +37 -13
- package/lib/config.js +3 -3
- package/lib/model.js +11 -2
- package/lib/request.js +18 -23
- package/lib/resourcerer.js +30 -36
- package/lib/sync.js +17 -16
- package/lib/utils.js +2 -2
- package/package.json +1 -1
- package/test/collection.test.js +32 -7
- package/test/model-mocks.js +7 -26
- package/test/model.test.js +22 -0
- package/test/prefetch.test.js +3 -3
- package/test/request.test.js +56 -21
- package/test/sync.test.js +49 -15
- package/test/utils.test.js +1 -0
package/lib/collection.js
CHANGED
|
@@ -22,17 +22,24 @@ export default class Collection {
|
|
|
22
22
|
* through the parse method and {silent: true} to not trigger any updates. in the default
|
|
23
23
|
* constructor, use:
|
|
24
24
|
*
|
|
25
|
-
* *
|
|
25
|
+
* * Model {Model} - dynamically overrides the static model property for the type of Model that
|
|
26
26
|
* this collection's models should be instances of
|
|
27
27
|
* * comparator {function|string} - dynamically overrides the static comparator property used to
|
|
28
28
|
* sort the collection
|
|
29
29
|
*/
|
|
30
30
|
constructor(models, options={}) {
|
|
31
|
-
|
|
31
|
+
const RESERVED_OPTION_KEYS = ['Model', 'comparator', 'silent', 'parse'];
|
|
32
|
+
|
|
33
|
+
this.Model = options.Model || this._getModelClass();
|
|
32
34
|
this.comparator = options.comparator || this.constructor.comparator;
|
|
33
35
|
|
|
34
36
|
this._reset();
|
|
35
37
|
|
|
38
|
+
this.urlOptions = Object.keys(options).reduce((memo, key) => Object.assign(
|
|
39
|
+
memo,
|
|
40
|
+
!RESERVED_OPTION_KEYS.includes(key) ? {[key]: options[key]} : {}
|
|
41
|
+
), {});
|
|
42
|
+
|
|
36
43
|
if (models) {
|
|
37
44
|
// silent for completeness, i guess. but a nothing triggered here because it's impossible for
|
|
38
45
|
// a listener to have been attached at this point
|
|
@@ -46,6 +53,13 @@ export default class Collection {
|
|
|
46
53
|
*/
|
|
47
54
|
static Model = Model
|
|
48
55
|
|
|
56
|
+
/**
|
|
57
|
+
* Defines the property by which we can uniquely identify models in the collection. Override this
|
|
58
|
+
* if you're not defining your own custom Model class but still need to index by a different field
|
|
59
|
+
* than the default ('id').
|
|
60
|
+
*/
|
|
61
|
+
static modelIdAttribute = null
|
|
62
|
+
|
|
49
63
|
/**
|
|
50
64
|
* This is a list of keys (could be attribute keys, but also keys passed in from the options
|
|
51
65
|
* object when instantiated) that resourcerer should take into account when determining how to
|
|
@@ -211,7 +225,7 @@ export default class Collection {
|
|
|
211
225
|
}
|
|
212
226
|
|
|
213
227
|
return this._byId[obj] ||
|
|
214
|
-
this._byId[
|
|
228
|
+
this._byId[(this._isModel(obj) ? obj.attributes : obj)[this.Model.idAttribute]] ||
|
|
215
229
|
obj.cid && this._byId[obj.cid];
|
|
216
230
|
}
|
|
217
231
|
|
|
@@ -410,14 +424,24 @@ export default class Collection {
|
|
|
410
424
|
}
|
|
411
425
|
|
|
412
426
|
/**
|
|
413
|
-
*
|
|
414
|
-
*
|
|
427
|
+
* This function gets called when the collection is instantiated, and its return value is set to
|
|
428
|
+
* its Model property (and used to instantiate all its models). It's only used if a `Model`
|
|
429
|
+
* option isn't passed to the constructor, and by default it returns the Model base class. But
|
|
430
|
+
* if the collection has a `modelIdAttribute` static property, it will create a new Model class
|
|
431
|
+
* with the corresponding `idAttribute` property and return that.
|
|
415
432
|
*
|
|
416
|
-
* @
|
|
417
|
-
* @return {string} that model's unique identifier
|
|
433
|
+
* @return {Model} model class associated with the collection
|
|
418
434
|
*/
|
|
419
|
-
|
|
420
|
-
|
|
435
|
+
_getModelClass() {
|
|
436
|
+
if (this.constructor.modelIdAttribute) {
|
|
437
|
+
let attr = this.constructor.modelIdAttribute;
|
|
438
|
+
|
|
439
|
+
return class extends Model {
|
|
440
|
+
static idAttribute = attr
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
return this.constructor.Model;
|
|
421
445
|
}
|
|
422
446
|
|
|
423
447
|
/**
|
|
@@ -475,8 +499,8 @@ export default class Collection {
|
|
|
475
499
|
|
|
476
500
|
delete this._byId[model.cid];
|
|
477
501
|
|
|
478
|
-
if (this.
|
|
479
|
-
delete this._byId[this.
|
|
502
|
+
if (model.attributes[this.Model.idAttribute]) {
|
|
503
|
+
delete this._byId[model.attributes[this.Model.idAttribute]];
|
|
480
504
|
}
|
|
481
505
|
|
|
482
506
|
removed.push(model);
|
|
@@ -507,7 +531,7 @@ export default class Collection {
|
|
|
507
531
|
_addReference(model) {
|
|
508
532
|
this._byId[model.cid] = model;
|
|
509
533
|
|
|
510
|
-
let id = this.
|
|
534
|
+
let id = model.attributes[this.Model.idAttribute];
|
|
511
535
|
|
|
512
536
|
if (id || typeof id === 'number') {
|
|
513
537
|
this._byId[id] = model;
|
|
@@ -526,7 +550,7 @@ export default class Collection {
|
|
|
526
550
|
_removeReference(model) {
|
|
527
551
|
delete this._byId[model.cid];
|
|
528
552
|
|
|
529
|
-
let id = this.
|
|
553
|
+
let id = model.attributes[this.Model.idAttribute];
|
|
530
554
|
|
|
531
555
|
if (id) {
|
|
532
556
|
delete this._byId[id];
|
package/lib/config.js
CHANGED
|
@@ -106,12 +106,12 @@ export const ResourcesConfig = {
|
|
|
106
106
|
* but that won't handle complex values (arrays and objects). To add support for that, override
|
|
107
107
|
* this method with any logic or stringify library you want.
|
|
108
108
|
*
|
|
109
|
-
* @param {object}
|
|
109
|
+
* @param {object} params - request params
|
|
110
110
|
* @param {object} options - request options map
|
|
111
111
|
* @return {string} URL query parameter string
|
|
112
112
|
*/
|
|
113
|
-
stringify(
|
|
114
|
-
return new URLSearchParams(
|
|
113
|
+
stringify(params, options) {
|
|
114
|
+
return new URLSearchParams(params).toString();
|
|
115
115
|
},
|
|
116
116
|
|
|
117
117
|
/** {function}: Hook to send resource request times to a tracking service. */
|
package/lib/model.js
CHANGED
|
@@ -19,12 +19,15 @@ export default class Model {
|
|
|
19
19
|
/**
|
|
20
20
|
* @param {object} attributes - initial server data representation to be kept on the model
|
|
21
21
|
* @param {object} options - generic map. in the default constructor, use:
|
|
22
|
+
* url() method
|
|
22
23
|
* * parse {boolean} - if true, runs the initial attributes through the parse function beefore
|
|
23
24
|
* setting on the model
|
|
24
25
|
* * collection {Collection} - links this model to a collection, if applicable
|
|
25
26
|
* * ...any other options that .set() takes
|
|
26
27
|
*/
|
|
27
28
|
constructor(attributes={}, options={}) {
|
|
29
|
+
const RESERVED_OPTION_KEYS = ['parse', 'collection', 'silent', 'unset'];
|
|
30
|
+
|
|
28
31
|
this.cid = uniqueId('c');
|
|
29
32
|
this.attributes = {};
|
|
30
33
|
|
|
@@ -36,6 +39,11 @@ export default class Model {
|
|
|
36
39
|
attributes = this.parse(attributes, options) || {};
|
|
37
40
|
}
|
|
38
41
|
|
|
42
|
+
this.urlOptions = Object.keys(options).reduce((memo, key) => Object.assign(
|
|
43
|
+
memo,
|
|
44
|
+
!RESERVED_OPTION_KEYS.includes(key) ? {[key]: options[key]} : {}
|
|
45
|
+
), {});
|
|
46
|
+
|
|
39
47
|
this.set({...result(this.constructor, 'defaults'), ...attributes}, options);
|
|
40
48
|
}
|
|
41
49
|
|
|
@@ -314,8 +322,9 @@ export default class Model {
|
|
|
314
322
|
*
|
|
315
323
|
* @return {string} the url endpoint to request for this particular model instance
|
|
316
324
|
*/
|
|
317
|
-
url() {
|
|
318
|
-
var base = result(this, 'urlRoot') || result(this.collection, 'url') ||
|
|
325
|
+
url(options=this.urlOptions) {
|
|
326
|
+
var base = result(this, 'urlRoot', options) || result(this.collection, 'url', options) ||
|
|
327
|
+
urlError();
|
|
319
328
|
|
|
320
329
|
if (this.isNew()) {
|
|
321
330
|
return base;
|
package/lib/request.js
CHANGED
|
@@ -35,12 +35,11 @@ export const existsInCache = (key) => !!ModelCache.get(key);
|
|
|
35
35
|
* @param {function} Model - the model constructor
|
|
36
36
|
* @param {object} options - options object used for fetching that can include:
|
|
37
37
|
*
|
|
38
|
-
* *
|
|
39
|
-
* *
|
|
38
|
+
* * data {object|object[]} - attributes or models to pass a Model or Collection instance, resp.
|
|
39
|
+
* * params {object} - query params to pass into the fetch method
|
|
40
40
|
* * fetch {boolean} - whether fetch the model after creation
|
|
41
|
-
* *
|
|
41
|
+
* * force {boolean} - force the fetch to be made if the model is already cached
|
|
42
42
|
* * method {string} - request type (GET|POST|PUT|DELETE)
|
|
43
|
-
* * models {array} - models to pass a Collection instance
|
|
44
43
|
* * options {object} - options to pass to the Model constructor
|
|
45
44
|
* * prefetch {boolean} - whether the request should be treated as a prefetched resource
|
|
46
45
|
*
|
|
@@ -52,24 +51,27 @@ export default (key, Model, options={}) => {
|
|
|
52
51
|
_promise;
|
|
53
52
|
|
|
54
53
|
options = {
|
|
55
|
-
|
|
56
|
-
|
|
54
|
+
data: Model && Model.prototype instanceof Collection ? [] : {},
|
|
55
|
+
params: {},
|
|
56
|
+
options: {},
|
|
57
57
|
fetch: true,
|
|
58
|
-
|
|
58
|
+
force: false,
|
|
59
|
+
lazy: false,
|
|
59
60
|
method: 'GET',
|
|
60
|
-
models: [],
|
|
61
61
|
...options
|
|
62
62
|
};
|
|
63
63
|
|
|
64
64
|
if (!loadingCache[key]) {
|
|
65
65
|
_promise = new Promise((resolve, reject) => {
|
|
66
|
-
if (!model || options.
|
|
67
|
-
model = model || new Model(options
|
|
66
|
+
if (!model || model.lazy || options.force) {
|
|
67
|
+
model = model || new Model(options.data, options.options);
|
|
68
68
|
|
|
69
|
-
if (options.fetch) {
|
|
69
|
+
if (options.fetch && !options.lazy) {
|
|
70
70
|
addToLoadingCache = true;
|
|
71
71
|
|
|
72
|
-
model.
|
|
72
|
+
delete model.lazy;
|
|
73
|
+
|
|
74
|
+
model.fetch({params: options.params}).then(
|
|
73
75
|
([newModel, response]) => {
|
|
74
76
|
delete loadingCache[key];
|
|
75
77
|
ModelCache.put(key, newModel, options.component);
|
|
@@ -81,6 +83,10 @@ export default (key, Model, options={}) => {
|
|
|
81
83
|
}
|
|
82
84
|
);
|
|
83
85
|
} else {
|
|
86
|
+
// lazy means resolove but don't fetch yet; it will get updates from other components
|
|
87
|
+
// we only want to do this if a model is not yet in the cache
|
|
88
|
+
options.lazy && !ModelCache.get(key) ? model.lazy = true : null;
|
|
89
|
+
|
|
84
90
|
ModelCache.put(key, model, options.component);
|
|
85
91
|
resolve([model]);
|
|
86
92
|
}
|
|
@@ -111,14 +117,3 @@ export default (key, Model, options={}) => {
|
|
|
111
117
|
// this way we can attach more .then() handlers
|
|
112
118
|
return loadingCache[key];
|
|
113
119
|
};
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Helper to determine whether to pass the `models` property or the `attributes`
|
|
117
|
-
* value of an options hash as a model instantiation's first argument.
|
|
118
|
-
*
|
|
119
|
-
* @param {Model|Collection} Constructor - model constructor
|
|
120
|
-
* @return {string} property name to pass to model instantiation
|
|
121
|
-
*/
|
|
122
|
-
export function getFirstArgPropertyName(Constructor) {
|
|
123
|
-
return Constructor.prototype instanceof Collection ? 'models' : 'attributes';
|
|
124
|
-
}
|
package/lib/resourcerer.js
CHANGED
|
@@ -33,8 +33,8 @@ const SPREAD_PROVIDES_CHAR = '_';
|
|
|
33
33
|
* * noncritical {boolean} - whether the resource should not be taken into
|
|
34
34
|
* account when determining the loading state of the component. default
|
|
35
35
|
* is false
|
|
36
|
-
* *
|
|
37
|
-
* * options {object} -
|
|
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
38
|
* * dependsOn {string[]} - prop fields required to be present before the
|
|
39
39
|
* resource will fetch
|
|
40
40
|
* * provides {object<string: function>[]} - list of props that a resource
|
|
@@ -44,6 +44,8 @@ const SPREAD_PROVIDES_CHAR = '_';
|
|
|
44
44
|
* a value to be set for the prop. If the key is equal to
|
|
45
45
|
* SPREAD_PROVIDES_CHAR, then the return value of the transform function
|
|
46
46
|
* is spread for dynamically-provided props.
|
|
47
|
+
* * force {boolean} - force a fetch request regardless of whether the model
|
|
48
|
+
* is already in the cache
|
|
47
49
|
* * prefetch {object} - an individual map of expected future props to fetch
|
|
48
50
|
* a new resource and store it in the cache. it will not, however, get
|
|
49
51
|
* passed down to the child (no loading states, either)
|
|
@@ -56,8 +58,8 @@ const SPREAD_PROVIDES_CHAR = '_';
|
|
|
56
58
|
* * ...any other option that can be passed directly to the `request` function
|
|
57
59
|
*/
|
|
58
60
|
export const useResources = (getResources, props) => {
|
|
59
|
-
var [
|
|
60
|
-
props = {...props, ...
|
|
61
|
+
var [resourceState, setResourceState] = useState({}),
|
|
62
|
+
props = {...props, ...resourceState},
|
|
61
63
|
resources = generateResources(getResources, props),
|
|
62
64
|
|
|
63
65
|
initialLoadingStates = buildResourcesLoadingState(resources.filter(withoutPrefetch), props),
|
|
@@ -173,7 +175,7 @@ export const useResources = (getResources, props) => {
|
|
|
173
175
|
// this is our re-caching: if we already have a new model in the cache that has now been
|
|
174
176
|
// saved (and thus has a real cache key), move the model to the new cache key and remove
|
|
175
177
|
// it from the old one. this will save an unnecessary request.
|
|
176
|
-
if (prevConfig.
|
|
178
|
+
if (prevConfig.data && !prevConfig.data?.id && config.data?.id) {
|
|
177
179
|
ModelCache.put(getCacheKey(config), ModelCache.get(prevCacheKey));
|
|
178
180
|
ModelCache.remove(prevCacheKey);
|
|
179
181
|
}
|
|
@@ -268,7 +270,7 @@ export const useResources = (getResources, props) => {
|
|
|
268
270
|
// precedence over all
|
|
269
271
|
...props,
|
|
270
272
|
...props[ResourcesConfig.queryParamsPropName] || {},
|
|
271
|
-
...
|
|
273
|
+
...resourceState,
|
|
272
274
|
|
|
273
275
|
// helpers
|
|
274
276
|
isOrWillBeLoading: () => {
|
|
@@ -407,12 +409,9 @@ function getResourcePropertyName(baseName, modelKey) {
|
|
|
407
409
|
* @return {Model|Collection} empty model or collection instance with frozen
|
|
408
410
|
* atributes or models, respectively
|
|
409
411
|
*/
|
|
410
|
-
function getEmptyModel({modelKey,
|
|
412
|
+
function getEmptyModel({modelKey, data, options}) {
|
|
411
413
|
var Model_ = typeof ModelMap[modelKey] === 'function' ? ModelMap[modelKey] : Model,
|
|
412
|
-
emptyInstance = new Model_(
|
|
413
|
-
Model_.prototype instanceof Collection ? models : attributes,
|
|
414
|
-
options
|
|
415
|
-
);
|
|
414
|
+
emptyInstance = new Model_(data, options);
|
|
416
415
|
|
|
417
416
|
// flag to differentiate between other model instances that happen to be empty
|
|
418
417
|
emptyInstance.isEmptyModel = true;
|
|
@@ -430,21 +429,21 @@ function getEmptyModel({modelKey, attributes, models, options}) {
|
|
|
430
429
|
* the constructor's static `cacheFields` array:
|
|
431
430
|
*
|
|
432
431
|
* `cacheFields` values are taken directly from the config object as opposed
|
|
433
|
-
* to props, in the following order: `options` object, `
|
|
434
|
-
* `
|
|
432
|
+
* to props, in the following order: `options` object, `data` object,
|
|
433
|
+
* `params` object. Field keys are included in this method, which is why it is
|
|
435
434
|
* preferred. `cacheFields` entries can be functions, too, which take the
|
|
436
|
-
* `
|
|
435
|
+
* `params` object as a parameter and return a key/value object that gets
|
|
437
436
|
* flattened to a piece of the cache key.
|
|
438
437
|
*
|
|
439
438
|
* @param {object} config - resource config object (destructured)
|
|
440
439
|
* @return {string} cache key
|
|
441
440
|
*/
|
|
442
|
-
export function getCacheKey({modelKey,
|
|
441
|
+
export function getCacheKey({modelKey, params={}, options={}, data={}}) {
|
|
443
442
|
var toKeyValString = ([key, val]) => val ? `${key}=${val}` : '',
|
|
444
443
|
fields = (ModelMap[modelKey]?.cacheFields || []).map(
|
|
445
444
|
(key) => typeof key === 'function' ?
|
|
446
|
-
Object.entries(key(
|
|
447
|
-
toKeyValString([key, options[key] ||
|
|
445
|
+
Object.entries(key(params)).map(toKeyValString).join('_') :
|
|
446
|
+
toKeyValString([key, options[key] || data[key] || params[key]])
|
|
448
447
|
).filter((x) => x);
|
|
449
448
|
|
|
450
449
|
return `${modelKey || ''}${fields.sort().join('_')}`;
|
|
@@ -470,7 +469,7 @@ function findConfig([name, {prefetch}], getResources, props) {
|
|
|
470
469
|
}
|
|
471
470
|
|
|
472
471
|
/**
|
|
473
|
-
* Our cache key generation
|
|
472
|
+
* Our cache key generation does not use props directly, which
|
|
474
473
|
* makes comparing current/next resources more difficult (ie, we can't just
|
|
475
474
|
* compare `getCacheKey(config, this.props)` and `getCacheKey(config, nextProps)`)
|
|
476
475
|
* directly because `config` itself is determined from props. However,
|
|
@@ -621,9 +620,9 @@ function useIsMounted() {
|
|
|
621
620
|
* before clearing the performance markers.
|
|
622
621
|
*
|
|
623
622
|
* @param {string} name - resource name
|
|
624
|
-
* @param {object<
|
|
623
|
+
* @param {object<params: object, options: object>} fetch params and props
|
|
625
624
|
*/
|
|
626
|
-
function trackRequestTime(name, {
|
|
625
|
+
function trackRequestTime(name, {params, options}) {
|
|
627
626
|
var measurementName = `${name}Fetch`,
|
|
628
627
|
fetchEntry;
|
|
629
628
|
|
|
@@ -634,7 +633,7 @@ function trackRequestTime(name, {data, options}) {
|
|
|
634
633
|
|
|
635
634
|
ResourcesConfig.track('API Fetch', {
|
|
636
635
|
Resource: name,
|
|
637
|
-
|
|
636
|
+
params,
|
|
638
637
|
options,
|
|
639
638
|
duration: Math.round(fetchEntry.duration)
|
|
640
639
|
});
|
|
@@ -684,7 +683,10 @@ function modelAggregator(resources) {
|
|
|
684
683
|
|
|
685
684
|
/**
|
|
686
685
|
* Separates out resources between those that are loading and those that have loaded. The latter
|
|
687
|
-
* won't need to get passed to fetchResources, but the former will.
|
|
686
|
+
* won't need to get passed to fetchResources, but the former will. Make sure that prefetched
|
|
687
|
+
* resources get added to those that are loading so that the request gets made. Since prefetched
|
|
688
|
+
* models don't factor into loading states, there's no concern that they get passed to
|
|
689
|
+
* fetchResources even if they have been cached.
|
|
688
690
|
*
|
|
689
691
|
* @param {array[]} resourcesToUpdate - resource configs to partition
|
|
690
692
|
* @param {object} loadingStates - contains upcoming loading states for each resource
|
|
@@ -693,7 +695,7 @@ function modelAggregator(resources) {
|
|
|
693
695
|
*/
|
|
694
696
|
function partitionResources(resourcesToUpdate, loadingStates) {
|
|
695
697
|
return resourcesToUpdate.reduce((memo, [name, config]) =>
|
|
696
|
-
config.refetch || !hasLoaded(loadingStates[getResourceState(name)]) ?
|
|
698
|
+
config.refetch || config.prefetch || !hasLoaded(loadingStates[getResourceState(name)]) ?
|
|
697
699
|
[memo[0], memo[1].concat([[name, config]])] :
|
|
698
700
|
[memo[0].concat([[name, config]]), memo[1]],
|
|
699
701
|
[[], []]);
|
|
@@ -760,11 +762,6 @@ function loaderReducer(
|
|
|
760
762
|
function shouldMeasureRequest(modelKey, config) {
|
|
761
763
|
if (!window.performance || !window.performance.mark) {
|
|
762
764
|
return false;
|
|
763
|
-
// this is legacy and undocumented, but allows measuring on an instance-basis,
|
|
764
|
-
// which can cause unpredictable behavior if two components request the same
|
|
765
|
-
// resource but only one has {measure: true} configured.
|
|
766
|
-
} else if (config.measure) {
|
|
767
|
-
return true;
|
|
768
765
|
}
|
|
769
766
|
|
|
770
767
|
return typeof ModelMap[modelKey].measure === 'function' ?
|
|
@@ -810,7 +807,7 @@ function fetchResources(resources, props, {
|
|
|
810
807
|
return Promise.all(
|
|
811
808
|
// nice visual for this promise chain: http://tinyurl.com/y6wt47b6
|
|
812
809
|
resources.map(([name, config]) => {
|
|
813
|
-
var {
|
|
810
|
+
var {params, modelKey, provides={}, refetch, ...rest} = config,
|
|
814
811
|
cacheKey = getCacheKey(config),
|
|
815
812
|
shouldMeasure = shouldMeasureRequest(modelKey, config) && !getModelFromCache(config);
|
|
816
813
|
|
|
@@ -820,9 +817,9 @@ function fetchResources(resources, props, {
|
|
|
820
817
|
|
|
821
818
|
return request(cacheKey, ModelMap[modelKey], {
|
|
822
819
|
fetch: !UnfetchedResources.has(modelKey),
|
|
823
|
-
|
|
820
|
+
params,
|
|
824
821
|
component,
|
|
825
|
-
|
|
822
|
+
force: refetch,
|
|
826
823
|
...rest
|
|
827
824
|
}).then(
|
|
828
825
|
// success callback, where we track request time and add any dependent props or models
|
|
@@ -842,13 +839,10 @@ function fetchResources(resources, props, {
|
|
|
842
839
|
// components may be listening to existing models, so only create
|
|
843
840
|
// new model if one does not currently exist
|
|
844
841
|
existingModel ?
|
|
845
|
-
existingModel.set(uConfig.
|
|
842
|
+
existingModel.set(uConfig.data) :
|
|
846
843
|
ModelCache.put(
|
|
847
844
|
uCacheKey,
|
|
848
|
-
new ModelMap[uConfig.modelKey](
|
|
849
|
-
uConfig.models || uConfig.attributes,
|
|
850
|
-
uConfig.options || {}
|
|
851
|
-
),
|
|
845
|
+
new ModelMap[uConfig.modelKey](uConfig.data, uConfig.options),
|
|
852
846
|
component
|
|
853
847
|
);
|
|
854
848
|
}
|
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
|
|
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.
|
|
25
|
-
{
|
|
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
|
-
* *
|
|
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
|
|
52
|
-
hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) &&
|
|
52
|
+
var hasParams = !!Object.keys(options.params || {}).length,
|
|
53
|
+
hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasParams;
|
|
53
54
|
|
|
54
|
-
if (options.method === 'GET' &&
|
|
55
|
+
if (options.method === 'GET' && hasParams) {
|
|
55
56
|
options.url += (options.url.indexOf('?') > -1 ? '&' : '?') +
|
|
56
|
-
ResourcesConfig.stringify(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
|
|
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.
|
|
72
|
-
options.
|
|
72
|
+
body: typeof options.params === 'string' ?
|
|
73
|
+
options.params :
|
|
73
74
|
options.contentType === MIME_TYPE_JSON ?
|
|
74
|
-
JSON.stringify(options.
|
|
75
|
-
ResourcesConfig.stringify(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
|
}
|
package/package.json
CHANGED
package/test/collection.test.js
CHANGED
|
@@ -43,6 +43,13 @@ describe('Collection', () => {
|
|
|
43
43
|
expect(collection.Model).toEqual(__Model);
|
|
44
44
|
});
|
|
45
45
|
|
|
46
|
+
it('unreserved option items are assigned to a `urlOptions` instance property', () => {
|
|
47
|
+
collection = new Collection([], {one: 1, two: 2, comparator: 'foo', parse: true});
|
|
48
|
+
|
|
49
|
+
expect(collection.urlOptions).toEqual({one: 1, two: 2});
|
|
50
|
+
expect(collection.toJSON()).toEqual([]);
|
|
51
|
+
});
|
|
52
|
+
|
|
46
53
|
it('adds any models passed to its models list', () => {
|
|
47
54
|
var model1 = new Model,
|
|
48
55
|
model2 = new Model;
|
|
@@ -610,21 +617,39 @@ describe('Collection', () => {
|
|
|
610
617
|
});
|
|
611
618
|
});
|
|
612
619
|
|
|
613
|
-
describe('
|
|
614
|
-
it('
|
|
620
|
+
describe('setting a model id attribute', () => {
|
|
621
|
+
it('on the model sets the id attributes for all models', () => {
|
|
615
622
|
class _Model extends Model {
|
|
616
623
|
static idAttribute = 'name'
|
|
617
624
|
}
|
|
618
625
|
|
|
626
|
+
// default is just id
|
|
627
|
+
collection = new Collection();
|
|
628
|
+
collection.add({id: 'noahgrant', name: 'Noah Grant'});
|
|
629
|
+
expect(collection.get('noahgrant')).toBeDefined();
|
|
630
|
+
expect(collection.get('Noah Grant')).not.toBeDefined();
|
|
631
|
+
expect(collection.get('noahgrant').id).toEqual('noahgrant');
|
|
632
|
+
expect(collection.Model.idAttribute).toEqual('id');
|
|
633
|
+
|
|
634
|
+
collection = new Collection([], {Model: _Model});
|
|
635
|
+
collection.add({id: 'noahgrant', name: 'Noah Grant'});
|
|
636
|
+
expect(collection.get('noahgrant')).not.toBeDefined();
|
|
637
|
+
expect(collection.get('Noah Grant')).toBeDefined();
|
|
638
|
+
expect(collection.get('Noah Grant').id).toEqual('Noah Grant');
|
|
639
|
+
expect(collection.Model.idAttribute).toEqual('name');
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
it('on the collection sets the id attribute for its models', () => {
|
|
619
643
|
class _Collection extends Collection {
|
|
620
|
-
static
|
|
644
|
+
static modelIdAttribute = 'name'
|
|
621
645
|
}
|
|
622
646
|
|
|
623
|
-
collection = new Collection();
|
|
624
|
-
expect(collection.modelId({id: 'noahgrant', name: 'Noah Grant'})).toEqual('noahgrant');
|
|
625
|
-
|
|
626
647
|
collection = new _Collection();
|
|
627
|
-
|
|
648
|
+
collection.add({id: 'noahgrant', name: 'Noah Grant'});
|
|
649
|
+
expect(collection.get('noahgrant')).not.toBeDefined();
|
|
650
|
+
expect(collection.get('Noah Grant')).toBeDefined();
|
|
651
|
+
expect(collection.get('Noah Grant').id).toEqual('Noah Grant');
|
|
652
|
+
expect(collection.Model.idAttribute).toEqual('name');
|
|
628
653
|
});
|
|
629
654
|
});
|
|
630
655
|
|
package/test/model-mocks.js
CHANGED
|
@@ -4,11 +4,10 @@ import Model from '../lib/model';
|
|
|
4
4
|
export class UserModel extends Model {
|
|
5
5
|
key = 'user'
|
|
6
6
|
|
|
7
|
-
constructor(
|
|
8
|
-
super(
|
|
7
|
+
constructor(attributes, options={}) {
|
|
8
|
+
super(attributes, options);
|
|
9
9
|
|
|
10
10
|
this.userId = options.userId;
|
|
11
|
-
this.fraudLevel = options.fraudLevel;
|
|
12
11
|
}
|
|
13
12
|
|
|
14
13
|
url() {
|
|
@@ -39,14 +38,8 @@ export class DecisionsCollection extends Collection {
|
|
|
39
38
|
export class NotesModel extends Model {
|
|
40
39
|
key = 'notes'
|
|
41
40
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
this.userId = options.userId;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
url() {
|
|
49
|
-
return `/root/${this.userId}/notes`;
|
|
41
|
+
url({userId}) {
|
|
42
|
+
return `/root/${userId}/notes`;
|
|
50
43
|
}
|
|
51
44
|
|
|
52
45
|
static cacheFields = ['userId']
|
|
@@ -55,17 +48,11 @@ export class NotesModel extends Model {
|
|
|
55
48
|
export class SearchQueryModel extends Model {
|
|
56
49
|
key = 'search'
|
|
57
50
|
|
|
58
|
-
constructor(attributes, options={}) {
|
|
59
|
-
super(attributes, options);
|
|
60
|
-
|
|
61
|
-
this.userId = options.userId;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
51
|
fetch(options={}) {
|
|
65
52
|
options = {
|
|
66
53
|
...options,
|
|
67
54
|
contentType: 'application/json',
|
|
68
|
-
|
|
55
|
+
params: JSON.stringify(options.params),
|
|
69
56
|
type: 'POST'
|
|
70
57
|
};
|
|
71
58
|
|
|
@@ -117,13 +104,7 @@ export class LabelInstanceModel extends Model {
|
|
|
117
104
|
export class AccountConfigModel extends Model {
|
|
118
105
|
key = 'accountConfig'
|
|
119
106
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
this.accountId = options.accountId;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
url() {
|
|
127
|
-
return `/root/accounts/${this.accountId}/config`;
|
|
107
|
+
url({accountId}) {
|
|
108
|
+
return `/root/accounts/${accountId}/config`;
|
|
128
109
|
}
|
|
129
110
|
}
|