resourcerer 1.0.0-beta-1 → 1.0.0-beta-5
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 +169 -133
- package/index.js +0 -6
- package/lib/collection.js +44 -13
- package/lib/config.js +3 -3
- package/lib/model.js +18 -2
- package/lib/prefetch.js +2 -2
- package/lib/request.js +7 -19
- package/lib/resourcerer.js +27 -35
- 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 +4 -4
- package/test/request.test.js +5 -13
- 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
|
|
@@ -54,6 +68,13 @@ export default class Collection {
|
|
|
54
68
|
*/
|
|
55
69
|
static cacheFields = []
|
|
56
70
|
|
|
71
|
+
/**
|
|
72
|
+
* Use this to tell resourcerer to track this collection's request time via the `track` method
|
|
73
|
+
* added in the resourcerer configuration file. This can be a boolean or a function that returns a
|
|
74
|
+
* boolean. If the latter, it takes a the resource config object as an argument.
|
|
75
|
+
*/
|
|
76
|
+
static measure = false
|
|
77
|
+
|
|
57
78
|
/**
|
|
58
79
|
* Similar to the method for an individual model, this maps through each model in the collection
|
|
59
80
|
* and returns its data attributes.
|
|
@@ -204,7 +225,7 @@ export default class Collection {
|
|
|
204
225
|
}
|
|
205
226
|
|
|
206
227
|
return this._byId[obj] ||
|
|
207
|
-
this._byId[
|
|
228
|
+
this._byId[(this._isModel(obj) ? obj.attributes : obj)[this.Model.idAttribute]] ||
|
|
208
229
|
obj.cid && this._byId[obj.cid];
|
|
209
230
|
}
|
|
210
231
|
|
|
@@ -403,14 +424,24 @@ export default class Collection {
|
|
|
403
424
|
}
|
|
404
425
|
|
|
405
426
|
/**
|
|
406
|
-
*
|
|
407
|
-
*
|
|
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.
|
|
408
432
|
*
|
|
409
|
-
* @
|
|
410
|
-
* @return {string} that model's unique identifier
|
|
433
|
+
* @return {Model} model class associated with the collection
|
|
411
434
|
*/
|
|
412
|
-
|
|
413
|
-
|
|
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;
|
|
414
445
|
}
|
|
415
446
|
|
|
416
447
|
/**
|
|
@@ -468,8 +499,8 @@ export default class Collection {
|
|
|
468
499
|
|
|
469
500
|
delete this._byId[model.cid];
|
|
470
501
|
|
|
471
|
-
if (this.
|
|
472
|
-
delete this._byId[this.
|
|
502
|
+
if (model.attributes[this.Model.idAttribute]) {
|
|
503
|
+
delete this._byId[model.attributes[this.Model.idAttribute]];
|
|
473
504
|
}
|
|
474
505
|
|
|
475
506
|
removed.push(model);
|
|
@@ -500,7 +531,7 @@ export default class Collection {
|
|
|
500
531
|
_addReference(model) {
|
|
501
532
|
this._byId[model.cid] = model;
|
|
502
533
|
|
|
503
|
-
let id = this.
|
|
534
|
+
let id = model.attributes[this.Model.idAttribute];
|
|
504
535
|
|
|
505
536
|
if (id || typeof id === 'number') {
|
|
506
537
|
this._byId[id] = model;
|
|
@@ -519,7 +550,7 @@ export default class Collection {
|
|
|
519
550
|
_removeReference(model) {
|
|
520
551
|
delete this._byId[model.cid];
|
|
521
552
|
|
|
522
|
-
let id = this.
|
|
553
|
+
let id = model.attributes[this.Model.idAttribute];
|
|
523
554
|
|
|
524
555
|
if (id) {
|
|
525
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
|
|
|
@@ -60,6 +68,13 @@ export default class Model {
|
|
|
60
68
|
*/
|
|
61
69
|
static defaults = {}
|
|
62
70
|
|
|
71
|
+
/**
|
|
72
|
+
* Use this to tell resourcerer to track this model's request time via the `track` method added
|
|
73
|
+
* in the resourcerer configuration file. This can be a boolean or a function that returns a
|
|
74
|
+
* boolean. If the latter, it takes a the resource config object as an argument.
|
|
75
|
+
*/
|
|
76
|
+
static measure = false
|
|
77
|
+
|
|
63
78
|
/**
|
|
64
79
|
* Returns a copy of the model's `attributes` object. Use this method to get the current entire
|
|
65
80
|
* server data representation.
|
|
@@ -307,8 +322,9 @@ export default class Model {
|
|
|
307
322
|
*
|
|
308
323
|
* @return {string} the url endpoint to request for this particular model instance
|
|
309
324
|
*/
|
|
310
|
-
url() {
|
|
311
|
-
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();
|
|
312
328
|
|
|
313
329
|
if (this.isNew()) {
|
|
314
330
|
return base;
|
package/lib/prefetch.js
CHANGED
|
@@ -13,14 +13,14 @@ const PREFETCH_TIMEOUT = 50;
|
|
|
13
13
|
*
|
|
14
14
|
* @param {function} getResources - function that takes props as an argument
|
|
15
15
|
* and should return a map of resources. Identical to those used in
|
|
16
|
-
* `withResources`
|
|
16
|
+
* `useResources`/`withResources`
|
|
17
17
|
* @param {object} expectedProps - props in the form expected when the resource
|
|
18
18
|
* would be needed
|
|
19
19
|
* @return {function} callback to be invoked onMouseEnter of appropriate DOM el
|
|
20
20
|
*/
|
|
21
21
|
export default (getResources, expectedProps={}) => {
|
|
22
22
|
var fetched,
|
|
23
|
-
resources = Object.entries(getResources(
|
|
23
|
+
resources = Object.entries(getResources(ResourceKeys, expectedProps) || {});
|
|
24
24
|
|
|
25
25
|
return (evt) => {
|
|
26
26
|
var {target} = evt,
|
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
|
* * forceFetch {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,24 @@ 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
|
forceFetch: false,
|
|
59
59
|
method: 'GET',
|
|
60
|
-
models: [],
|
|
61
60
|
...options
|
|
62
61
|
};
|
|
63
62
|
|
|
64
63
|
if (!loadingCache[key]) {
|
|
65
64
|
_promise = new Promise((resolve, reject) => {
|
|
66
65
|
if (!model || options.forceFetch) {
|
|
67
|
-
model = model || new Model(options
|
|
66
|
+
model = model || new Model(options.data, options.options);
|
|
68
67
|
|
|
69
68
|
if (options.fetch) {
|
|
70
69
|
addToLoadingCache = true;
|
|
71
70
|
|
|
72
|
-
model.fetch({
|
|
71
|
+
model.fetch({params: options.params}).then(
|
|
73
72
|
([newModel, response]) => {
|
|
74
73
|
delete loadingCache[key];
|
|
75
74
|
ModelCache.put(key, newModel, options.component);
|
|
@@ -111,14 +110,3 @@ export default (key, Model, options={}) => {
|
|
|
111
110
|
// this way we can attach more .then() handlers
|
|
112
111
|
return loadingCache[key];
|
|
113
112
|
};
|
|
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
|
|
@@ -56,8 +56,8 @@ const SPREAD_PROVIDES_CHAR = '_';
|
|
|
56
56
|
* * ...any other option that can be passed directly to the `request` function
|
|
57
57
|
*/
|
|
58
58
|
export const useResources = (getResources, props) => {
|
|
59
|
-
var [
|
|
60
|
-
props = {...props, ...
|
|
59
|
+
var [resourceState, setResourceState] = useState({}),
|
|
60
|
+
props = {...props, ...resourceState},
|
|
61
61
|
resources = generateResources(getResources, props),
|
|
62
62
|
|
|
63
63
|
initialLoadingStates = buildResourcesLoadingState(resources.filter(withoutPrefetch), props),
|
|
@@ -173,7 +173,7 @@ export const useResources = (getResources, props) => {
|
|
|
173
173
|
// this is our re-caching: if we already have a new model in the cache that has now been
|
|
174
174
|
// saved (and thus has a real cache key), move the model to the new cache key and remove
|
|
175
175
|
// it from the old one. this will save an unnecessary request.
|
|
176
|
-
if (prevConfig.
|
|
176
|
+
if (prevConfig.data && !prevConfig.data?.id && config.data?.id) {
|
|
177
177
|
ModelCache.put(getCacheKey(config), ModelCache.get(prevCacheKey));
|
|
178
178
|
ModelCache.remove(prevCacheKey);
|
|
179
179
|
}
|
|
@@ -268,7 +268,7 @@ export const useResources = (getResources, props) => {
|
|
|
268
268
|
// precedence over all
|
|
269
269
|
...props,
|
|
270
270
|
...props[ResourcesConfig.queryParamsPropName] || {},
|
|
271
|
-
...
|
|
271
|
+
...resourceState,
|
|
272
272
|
|
|
273
273
|
// helpers
|
|
274
274
|
isOrWillBeLoading: () => {
|
|
@@ -407,12 +407,9 @@ function getResourcePropertyName(baseName, modelKey) {
|
|
|
407
407
|
* @return {Model|Collection} empty model or collection instance with frozen
|
|
408
408
|
* atributes or models, respectively
|
|
409
409
|
*/
|
|
410
|
-
function getEmptyModel({modelKey,
|
|
410
|
+
function getEmptyModel({modelKey, data, options}) {
|
|
411
411
|
var Model_ = typeof ModelMap[modelKey] === 'function' ? ModelMap[modelKey] : Model,
|
|
412
|
-
emptyInstance = new Model_(
|
|
413
|
-
Model_.prototype instanceof Collection ? models : attributes,
|
|
414
|
-
options
|
|
415
|
-
);
|
|
412
|
+
emptyInstance = new Model_(data, options);
|
|
416
413
|
|
|
417
414
|
// flag to differentiate between other model instances that happen to be empty
|
|
418
415
|
emptyInstance.isEmptyModel = true;
|
|
@@ -430,21 +427,21 @@ function getEmptyModel({modelKey, attributes, models, options}) {
|
|
|
430
427
|
* the constructor's static `cacheFields` array:
|
|
431
428
|
*
|
|
432
429
|
* `cacheFields` values are taken directly from the config object as opposed
|
|
433
|
-
* to props, in the following order: `options` object, `
|
|
434
|
-
* `
|
|
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
|
|
435
432
|
* preferred. `cacheFields` entries can be functions, too, which take the
|
|
436
|
-
* `
|
|
433
|
+
* `params` object as a parameter and return a key/value object that gets
|
|
437
434
|
* flattened to a piece of the cache key.
|
|
438
435
|
*
|
|
439
436
|
* @param {object} config - resource config object (destructured)
|
|
440
437
|
* @return {string} cache key
|
|
441
438
|
*/
|
|
442
|
-
export function getCacheKey({modelKey,
|
|
439
|
+
export function getCacheKey({modelKey, params={}, options={}, data={}}) {
|
|
443
440
|
var toKeyValString = ([key, val]) => val ? `${key}=${val}` : '',
|
|
444
441
|
fields = (ModelMap[modelKey]?.cacheFields || []).map(
|
|
445
442
|
(key) => typeof key === 'function' ?
|
|
446
|
-
Object.entries(key(
|
|
447
|
-
toKeyValString([key, options[key] ||
|
|
443
|
+
Object.entries(key(params)).map(toKeyValString).join('_') :
|
|
444
|
+
toKeyValString([key, options[key] || data[key] || params[key]])
|
|
448
445
|
).filter((x) => x);
|
|
449
446
|
|
|
450
447
|
return `${modelKey || ''}${fields.sort().join('_')}`;
|
|
@@ -470,7 +467,7 @@ function findConfig([name, {prefetch}], getResources, props) {
|
|
|
470
467
|
}
|
|
471
468
|
|
|
472
469
|
/**
|
|
473
|
-
* Our cache key generation
|
|
470
|
+
* Our cache key generation does not use props directly, which
|
|
474
471
|
* makes comparing current/next resources more difficult (ie, we can't just
|
|
475
472
|
* compare `getCacheKey(config, this.props)` and `getCacheKey(config, nextProps)`)
|
|
476
473
|
* directly because `config` itself is determined from props. However,
|
|
@@ -621,9 +618,9 @@ function useIsMounted() {
|
|
|
621
618
|
* before clearing the performance markers.
|
|
622
619
|
*
|
|
623
620
|
* @param {string} name - resource name
|
|
624
|
-
* @param {object<
|
|
621
|
+
* @param {object<params: object, options: object>} fetch params and props
|
|
625
622
|
*/
|
|
626
|
-
function trackRequestTime(name, {
|
|
623
|
+
function trackRequestTime(name, {params, options}) {
|
|
627
624
|
var measurementName = `${name}Fetch`,
|
|
628
625
|
fetchEntry;
|
|
629
626
|
|
|
@@ -634,7 +631,7 @@ function trackRequestTime(name, {data, options}) {
|
|
|
634
631
|
|
|
635
632
|
ResourcesConfig.track('API Fetch', {
|
|
636
633
|
Resource: name,
|
|
637
|
-
|
|
634
|
+
params,
|
|
638
635
|
options,
|
|
639
636
|
duration: Math.round(fetchEntry.duration)
|
|
640
637
|
});
|
|
@@ -684,7 +681,10 @@ function modelAggregator(resources) {
|
|
|
684
681
|
|
|
685
682
|
/**
|
|
686
683
|
* 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.
|
|
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.
|
|
688
688
|
*
|
|
689
689
|
* @param {array[]} resourcesToUpdate - resource configs to partition
|
|
690
690
|
* @param {object} loadingStates - contains upcoming loading states for each resource
|
|
@@ -693,7 +693,7 @@ function modelAggregator(resources) {
|
|
|
693
693
|
*/
|
|
694
694
|
function partitionResources(resourcesToUpdate, loadingStates) {
|
|
695
695
|
return resourcesToUpdate.reduce((memo, [name, config]) =>
|
|
696
|
-
config.refetch || !hasLoaded(loadingStates[getResourceState(name)]) ?
|
|
696
|
+
config.refetch || config.prefetch || !hasLoaded(loadingStates[getResourceState(name)]) ?
|
|
697
697
|
[memo[0], memo[1].concat([[name, config]])] :
|
|
698
698
|
[memo[0].concat([[name, config]]), memo[1]],
|
|
699
699
|
[[], []]);
|
|
@@ -760,11 +760,6 @@ function loaderReducer(
|
|
|
760
760
|
function shouldMeasureRequest(modelKey, config) {
|
|
761
761
|
if (!window.performance || !window.performance.mark) {
|
|
762
762
|
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
763
|
}
|
|
769
764
|
|
|
770
765
|
return typeof ModelMap[modelKey].measure === 'function' ?
|
|
@@ -810,7 +805,7 @@ function fetchResources(resources, props, {
|
|
|
810
805
|
return Promise.all(
|
|
811
806
|
// nice visual for this promise chain: http://tinyurl.com/y6wt47b6
|
|
812
807
|
resources.map(([name, config]) => {
|
|
813
|
-
var {
|
|
808
|
+
var {params, modelKey, provides={}, refetch, ...rest} = config,
|
|
814
809
|
cacheKey = getCacheKey(config),
|
|
815
810
|
shouldMeasure = shouldMeasureRequest(modelKey, config) && !getModelFromCache(config);
|
|
816
811
|
|
|
@@ -820,7 +815,7 @@ function fetchResources(resources, props, {
|
|
|
820
815
|
|
|
821
816
|
return request(cacheKey, ModelMap[modelKey], {
|
|
822
817
|
fetch: !UnfetchedResources.has(modelKey),
|
|
823
|
-
|
|
818
|
+
params,
|
|
824
819
|
component,
|
|
825
820
|
forceFetch: refetch,
|
|
826
821
|
...rest
|
|
@@ -842,13 +837,10 @@ function fetchResources(resources, props, {
|
|
|
842
837
|
// components may be listening to existing models, so only create
|
|
843
838
|
// new model if one does not currently exist
|
|
844
839
|
existingModel ?
|
|
845
|
-
existingModel.set(uConfig.
|
|
840
|
+
existingModel.set(uConfig.data) :
|
|
846
841
|
ModelCache.put(
|
|
847
842
|
uCacheKey,
|
|
848
|
-
new ModelMap[uConfig.modelKey](
|
|
849
|
-
uConfig.models || uConfig.attributes,
|
|
850
|
-
uConfig.options || {}
|
|
851
|
-
),
|
|
843
|
+
new ModelMap[uConfig.modelKey](uConfig.data, uConfig.options),
|
|
852
844
|
component
|
|
853
845
|
);
|
|
854
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
|
|
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
|
}
|