resourcerer 1.2.1 → 1.2.2

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 CHANGED
@@ -374,11 +374,11 @@ export default class UserModel extends Model {
374
374
  return `/users/${userId}`;
375
375
  }
376
376
 
377
- static cacheFields = ['userId']
377
+ static dependencies = ['userId'];
378
378
  }
379
379
  ```
380
380
 
381
- The `cacheFields` static property is important here, as we'll see in a second; it is a list of properties that `resourcerer` will use to generate a cache key for the model. It will look for the `userId` property in the following places, in order:
381
+ The `dependencies` static property is important here, as we'll see in a second; it is a list of properties that `resourcerer` will use to generate a cache key for the model. It will look for the `userId` property in the following places, in order:
382
382
 
383
383
  1. the `options` object
384
384
  1. the `data` object
@@ -422,7 +422,7 @@ In general, there are two ways to change `props.id` as in the previous example:
422
422
 
423
423
  ### params
424
424
 
425
- The `params` option is passed directly to the [sync method](/docs/model.md#sync) and sent either as stringified query params (GET requests) or as a body (POST/PUT). Its properties are also referenced when generating a cache key if they are listed in a model's static `cacheFields` property (See the [cache key section](#declarative-cache-keys) for more). Let's imagine that we have a lot of users and a lot of todos per user. So many that we only want to fetch the todos over a time range selected from a dropdown, sorted by a field also selected by a dropdown. These are query parameters we'd want to pass in our `params` property:
425
+ The `params` option is passed directly to the [sync method](/docs/model.md#sync) and sent either as stringified query params (GET requests) or as a body (POST/PUT). Its properties are also referenced when generating a cache key if they are listed in a model's static `dependencies` property (See the [cache key section](#declarative-cache-keys) for more). Let's imagine that we have a lot of users and a lot of todos per user. So many that we only want to fetch the todos over a time range selected from a dropdown, sorted by a field also selected by a dropdown. These are query parameters we'd want to pass in our `params` property:
426
426
 
427
427
  ```js
428
428
  @withResources((ResourceKeys, props) => {
@@ -442,14 +442,14 @@ The `params` option is passed directly to the [sync method](/docs/model.md#sync)
442
442
  class UserTodos extends React.Component {}
443
443
  ```
444
444
 
445
- Now, as the prop fields change, the params sent with the request changes as well (provided we set our `cacheFields` property accordingly):
445
+ Now, as the prop fields change, the params sent with the request changes as well (provided we set our `dependencies` property accordingly):
446
446
 
447
447
  `https://example.com/users/noahgrant/todos?limit=20&end_time=1494611831024&start_time=1492019831024&sort_field=importance`
448
448
 
449
449
 
450
450
  ### options
451
451
 
452
- [As referenced previously](#requesting-prop-driven-data), all properties on an `options` object will be passed into a model's/collection's `url` function. This makes it an ideal place to add _path parameters_ (contrast this with the [`params` object](#params), which is the place to add query (GET) or body (POST/PUT/PATCH) parameters). It will also be used in cache key generation if it has any fields specified in the model's static `cacheFields` property (See the [cache key section](#declarative-cache-keys) for more). Continuing with our User Todos example, let's add an `options` property:
452
+ [As referenced previously](#requesting-prop-driven-data), all properties on an `options` object will be passed into a model's/collection's `url` function. This makes it an ideal place to add _path parameters_ (contrast this with the [`params` object](#params), which is the place to add query (GET) or body (POST/PUT/PATCH) parameters). It will also be used in cache key generation if it has any fields specified in the model's static `dependencies` property (See the [cache key section](#declarative-cache-keys) for more). Continuing with our User Todos example, let's add an `options` property:
453
453
 
454
454
  ```js
455
455
  const getResources = (ResourceKeys, props) => {
@@ -469,7 +469,7 @@ const getResources = (ResourceKeys, props) => {
469
469
  };
470
470
  ```
471
471
 
472
- Here, this UserTodosCollection instance will get a `userId` property passed to both its `url` function as well as the options in its [constructor method](/docs/collection.md#constructor). We'll also want to add the `'userId'` string to the collection's [static `cacheFields` array](#requesting-prop-driven-data), because each cached collection should be specific to the user:
472
+ Here, this UserTodosCollection instance will get a `userId` property passed to both its `url` function as well as the options in its [constructor method](/docs/collection.md#constructor). We'll also want to add the `'userId'` string to the collection's [static `dependencies` array](#requesting-prop-driven-data), because each cached collection should be specific to the user:
473
473
 
474
474
  ```js
475
475
  // js/models/user_todos_collection.js
@@ -479,7 +479,7 @@ export class UserTodosCollection extends Collection {
479
479
  return `/users/${userId}/todos`;
480
480
  }
481
481
 
482
- static cacheFields = ['userId']
482
+ static dependencies = ['userId'];
483
483
  };
484
484
  ```
485
485
 
@@ -560,7 +560,7 @@ const getResources = (ResourceKeys, props) => {
560
560
 
561
561
  When the user clicks on a 'next' arrow that updates page state, the collection will already be in the cache, and it will get passed as the new `userTodosCollection`. Accordingly, the third page will then get prefetched (`props.page` equal to 2 and `from` equal to 40). Two important things to note here:
562
562
 
563
- 1. Don't forget to add `from` to the [`cacheFields`](#declarative-cache-keys) list!
563
+ 1. Don't forget to add `from` to the [`dependencies`](#declarative-cache-keys) list!
564
564
  1. The prefetched model does not get components registered to it; therefore, it is immediately scheduled for removal after the specified [cacheGracePeriod](#configuring). If the user clicks the next arrow, it then becomes the 'active' model and the `UserTodos` component will get registered to it, clearing the removal timer (see the [caching](caching-resources-with-modelcache) section).
565
565
 
566
566
  If you're looking to optimistically prefetch resources when a user hovers, say, over a link, see the [Prefetch on Hover](#prefetch-on-hover) section.
@@ -582,7 +582,7 @@ function MyCustomerComponent(props) {
582
582
 
583
583
  You can also use `data` to take advantage of [re-caching](/docs/advanced_topics.md#recaching-newly-saved-models).
584
584
 
585
- Like `params` and `options`, the `data` object will also be used in cache key generation if it has any fields specified in the model's static `cacheFields` property (See the [cache key section](#declarative-cache-keys) for more). For [Collections](/docs/collection.md#constructor), there is an equivalent `models` property, but again, these are seldom used.
585
+ Like `params` and `options`, the `data` object will also be used in cache key generation if it has any fields specified in the model's static `dependencies` property (See the [cache key section](#declarative-cache-keys) for more). For [Collections](/docs/collection.md#constructor), there is an equivalent `models` property, but again, these are seldom used.
586
586
 
587
587
  ### lazy
588
588
 
@@ -812,7 +812,7 @@ Again, it’s unlikely that you’ll use `ModelCache` directly while using `reso
812
812
 
813
813
  ## Declarative Cache Keys
814
814
 
815
- As alluded to previously, `resourcerer` relies on the model classes themselves to tell it how it should be cached. This is accomplished via a static `cacheFields` array, where each entry can be either:
815
+ As alluded to previously, `resourcerer` relies on the model classes themselves to tell it how it should be cached. This is accomplished via a static `dependencies` array, where each entry can be either:
816
816
 
817
817
  1. A string, where each string is the name of a property that the model receives whose value should take part in the cache key. The model can receive this property either from the [options](#options) hash, the [data](#data) hash, or the [params](#params) hash, in that order.
818
818
 
@@ -847,18 +847,18 @@ export class UserTodosCollection extends Collection {
847
847
  }
848
848
  // ...
849
849
 
850
- static cacheFields = [
850
+ static dependencies = [
851
851
  'limit',
852
852
  'userId',
853
853
  'sort_field',
854
854
  ({end_millis, start_millis}) => ({range: end_millis - start_millis})
855
- ]
855
+ ];
856
856
  };
857
857
  ```
858
858
 
859
- We can see that `limit` and `sort_field` as specified in `cacheFields` are taken straight from the `params` object that `resourcerer` transforms into url query parameters. `userId` is part of the `/users/{userId}/todos` path, so it can't be part of the `params` object, which is why it's stored as an instance property. But `resourcerer` will see its value within the `options` hash that is passed and use it for the cache key.
859
+ We can see that `limit` and `sort_field` as specified in `dependencies` are taken straight from the `params` object that `resourcerer` transforms into url query parameters. `userId` is part of the `/users/{userId}/todos` path, so it can't be part of the `params` object, which is why it's stored as an instance property. But `resourcerer` will see its value within the `options` hash that is passed and use it for the cache key.
860
860
 
861
- The time range is a little tougher to cache, though. We're less interested the spcecific `end_time`/`start_time` values to the millisecond—it does us little good to cache an endpoint tied to `Date.now()` when it will never be the same for the next request. We're much more interested in the difference between `end_time` and `start_time`. This is a great use-case for a function entry in `cacheFields`, which takes the `params` object passed an argument. In the case above, the returned object will contribute a key called `range` and a value equal to the time range to the cache key.
861
+ The time range is a little tougher to cache, though. We're less interested the spcecific `end_time`/`start_time` values to the millisecond—it does us little good to cache an endpoint tied to `Date.now()` when it will never be the same for the next request. We're much more interested in the difference between `end_time` and `start_time`. This is a great use-case for a function entry in `dependencies`, which takes the `params` object passed an argument. In the case above, the returned object will contribute a key called `range` and a value equal to the time range to the cache key.
862
862
 
863
863
  The generated cache key would be something like `userTodos_limit=50_$range=86400000_sort_field=importance_userId=noah`. Again, note that:
864
864
 
@@ -930,10 +930,10 @@ import {Model} from 'resourcerer';
930
930
 
931
931
  class MyMeasuredModel extends Model {
932
932
  // either a boolean, which will track every request of this model instance
933
- static measure = true
933
+ static measure = true;
934
934
 
935
935
  // or a function that returns a boolean, which will track instance requests based on a condition
936
- static measure = ({data={}}) => data.id === 'noahgrant'
936
+ static measure = ({data={}}) => data.id === 'noahgrant';
937
937
  }
938
938
  ```
939
939
 
@@ -1051,7 +1051,7 @@ ResourcesConfig.set(configObj);
1051
1051
  // not component-specific, so they should be defined on the model instead of the component
1052
1052
  // todos-collection.js
1053
1053
  export default class TodosCollection extends Collection {
1054
- static cacheFields = ['category']
1054
+ static dependencies = ['category'];
1055
1055
 
1056
1056
  url() {
1057
1057
  return '/todos';
@@ -28,7 +28,7 @@ Using `dependsOn` in simple cases like the one highlighted in the [README](https
28
28
 
29
29
  1. When a previously-`PENDING` but currently `LOADED` resource has its dependent prop removed, it goes back to a `PENDING` state (recall that if the dependent prop is changed, it gets put back into a `LOADING` state while the new resource is fetched). This puts us in an interesting state:
30
30
 
31
- 1. `hasInitiallyLoaded` will remain true, as expected. But the `PENDING` resource’s prop—assuming the resource’s `cacheFields` list includes the dependent prop—will now return to the empty model/collection, so any child component that may remain in place after `hasInitiallyLoaded` may need to keep that in mind (if `shouldComponentUpdate` returns false when the new resource fetches, then this shouldn’t matter—see the next point).
31
+ 1. `hasInitiallyLoaded` will remain true, as expected. But the `PENDING` resource’s prop—assuming the resource’s `dependencies` list includes the dependent prop—will now return to the empty model/collection, so any child component that may remain in place after `hasInitiallyLoaded` may need to keep that in mind (if `shouldComponentUpdate` returns false when the new resource fetches, then this shouldn’t matter—see the next point).
32
32
 
33
33
  2. Recall that we can provide the dependent prop in one of two ways:
34
34
  1. We can include it in another resource’s `provides` property, in which case the dependent prop gets set as state within resourcerer.
@@ -76,7 +76,7 @@ Using `dependsOn` in simple cases like the one highlighted in the [README](https
76
76
  ```
77
77
 
78
78
 
79
- 4. In the case that the model's `cacheFields` does not include the dependent prop (ie, the prop is used solely for triggering the resource request and doesn't factor into the request data), the model will still exist in the cache when the dependent prop is removed. In this case, the loading state is still returned to PENDING, but the existing model will also be present in the return value.
79
+ 4. In the case that the model's `dependencies` does not include the dependent prop (ie, the prop is used solely for triggering the resource request and doesn't factor into the request data), the model will still exist in the cache when the dependent prop is removed. In this case, the loading state is still returned to PENDING, but the existing model will also be present in the return value.
80
80
 
81
81
  ## Implicit dependent resources
82
82
 
@@ -140,7 +140,7 @@ export default class AccountModel extends Model {
140
140
  return `/accounts/${this.accountId}`;
141
141
  }
142
142
 
143
- static cacheFields = ['accountId']
143
+ static dependencies = ['accountId'];
144
144
 
145
145
  static providesModels = (accountModel, ResourceKeys) => [{
146
146
  data: accountModel.get('config'),
@@ -174,7 +174,7 @@ The resource config objects within `providesModels` have the same schema, as men
174
174
  // account_model.js
175
175
  export default class AccountModel extends Model {
176
176
  // ...
177
- static cacheFields: ['accountId']
177
+ static dependencies = ['accountId'];
178
178
 
179
179
  static providesModels = (accountModel, ResourceKeys) => [{
180
180
  data: accountModel.get('config'),
@@ -37,7 +37,7 @@ This is an instance property that represents the number of models in the collect
37
37
 
38
38
  Set this property if you want a collection's models to be an instance of a class other than the default Model
39
39
 
40
- ### `static` cacheFields
40
+ ### `static` dependencies
41
41
 
42
42
  This property tells resourcerer how to determine whether to make a new request or to take a collection out of the cache. It is an array of strings or functions from which its cache key is calculated. See the [cacheKey](https://github.com/noahgrant/resourcerer#caching-resources-with-modelcache) section for more info.
43
43
 
package/docs/model.md CHANGED
@@ -40,7 +40,7 @@ that you might find useful in rendering your data-hydrated components.
40
40
 
41
41
  ## Properties
42
42
 
43
- ### `static` cacheFields
43
+ ### `static` dependencies
44
44
  `Array<string|function>`
45
45
 
46
46
  This property tells resourcerer how to determine whether to make a new request or to take a model out of the cache. It is an array of strings or functions from which its cache key is calculated. See the [cacheKey](https://github.com/noahgrant/resourcerer#caching-resources-with-modelcache) section for more info.
package/index.d.ts CHANGED
@@ -74,6 +74,8 @@ declare module 'resourcerer' {
74
74
 
75
75
  static cacheFields: Array<string | ((attrs: T) => Record<string, any>)>;
76
76
 
77
+ static dependencies: Array<string | ((attrs: T) => Record<string, any>)>;
78
+
77
79
  static cacheTimeout: number;
78
80
 
79
81
  static idAttribute: string;
@@ -148,6 +150,8 @@ declare module 'resourcerer' {
148
150
 
149
151
  static cacheFields: Array<string | ((attrs: T) => Record<string, any>)>;
150
152
 
153
+ static dependencies: Array<string | ((attrs: T) => Record<string, any>)>;
154
+
151
155
  static modelIdAttribute: string;
152
156
 
153
157
  static measure: boolean | (() => void);
package/lib/collection.js CHANGED
@@ -66,6 +66,9 @@ export default class Collection {
66
66
  * cache a model and consider models to be identical. Can also be a function that returns an
67
67
  * object.
68
68
  */
69
+ static dependencies = []
70
+
71
+ // deprecated
69
72
  static cacheFields = []
70
73
 
71
74
  /**
package/lib/model.js CHANGED
@@ -69,6 +69,9 @@ export default class Model {
69
69
  * cache a model and consider models to be identical. Can also be a function that returns an
70
70
  * object.
71
71
  */
72
+ static dependencies = []
73
+
74
+ // deprecated
72
75
  static cacheFields = []
73
76
 
74
77
  /**
@@ -474,21 +474,26 @@ function getEmptyModel({modelKey, data, options}) {
474
474
  /**
475
475
  * Calculates a cache key for the resource depending on the base resource type
476
476
  * key and the truthy parameter values. Parameter values are calculated in via
477
- * the constructor's static `cacheFields` array:
477
+ * the constructor's static `dependencies` array:
478
478
  *
479
- * `cacheFields` values are taken directly from the config object as opposed
479
+ * `dependencies` values are taken directly from the config object as opposed
480
480
  * to props, in the following order: `options` object, `data` object,
481
481
  * `params` object. Field keys are included in this method, which is why it is
482
- * preferred. `cacheFields` entries can be functions, too, which take the
482
+ * preferred. `dependencies` entries can be functions, too, which take the
483
483
  * `params` object as a parameter and return a key/value object that gets
484
484
  * flattened to a piece of the cache key.
485
485
  *
486
+ * We also support the deprecated `cacheFields` instead.
487
+ *
486
488
  * @param {object} config - resource config object (destructured)
487
489
  * @return {string} cache key
488
490
  */
489
491
  export function getCacheKey({modelKey, params={}, options={}, data={}}) {
490
492
  var toKeyValString = ([key, val]) => val ? `${key}=${val}` : '',
491
- fields = (ModelMap[modelKey]?.cacheFields || []).map(
493
+ dependencies = ModelMap[modelKey]?.dependencies?.length ?
494
+ ModelMap[modelKey].dependencies :
495
+ ModelMap[modelKey]?.cacheFields || [],
496
+ fields = dependencies.map(
492
497
  (key) => typeof key === 'function' ?
493
498
  Object.entries(key(params)).map(toKeyValString).join('_') :
494
499
  toKeyValString([key, options[key] || data[key] || params[key]])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "1.2.1",
3
+ "version": "1.2.2",
4
4
  "repository": "github.com/noahgrant/resourcerer",
5
5
  "description": "Declarative data-fetching and caching framework for React",
6
6
  "keywords": ["declarative data-fetching framework", "react"],
@@ -14,7 +14,7 @@ export class UserModel extends Model {
14
14
  return `/root/users/${this.userId}`;
15
15
  }
16
16
 
17
- static cacheFields = ['fraudLevel', 'userId', 'id']
17
+ static dependencies = ['fraudLevel', 'userId', 'id']
18
18
  }
19
19
 
20
20
  export class AnalystsCollection extends Collection {
@@ -63,7 +63,7 @@ export class SearchQueryModel extends Model {
63
63
  return '/root/search';
64
64
  }
65
65
 
66
- static cacheFields = ['type', 'detailed', 'filter', 'sort', 'limit', 'from']
66
+ static dependencies = ['type', 'detailed', 'filter', 'sort', 'limit', 'from']
67
67
  }
68
68
 
69
69
  export class SignalsCollection extends Collection {
@@ -94,11 +94,11 @@ export class DecisionLogsCollection extends Collection {
94
94
 
95
95
  // next three are unfetched resources
96
96
  export class DecisionInstanceModel extends Model {
97
- static cacheFields = ['entityType', 'entityId']
97
+ static dependencies = ['entityType', 'entityId']
98
98
  }
99
99
 
100
100
  export class LabelInstanceModel extends Model {
101
- static cacheFields = ['userId']
101
+ static dependencies = ['userId']
102
102
  }
103
103
 
104
104
  export class AccountConfigModel extends Model {
@@ -28,6 +28,7 @@ describe('Model', () => {
28
28
  it('has expected default static properties', () => {
29
29
  expect(Model.idAttribute).toEqual('id');
30
30
  expect(Model.cacheFields).toEqual([]);
31
+ expect(Model.dependencies).toEqual([]);
31
32
  expect(Model.defaults).toEqual({});
32
33
  });
33
34
 
@@ -31,8 +31,33 @@ describe('prefetch', () => {
31
31
  });
32
32
 
33
33
  it('correctly turns the config object into cache key, params, and options', () => {
34
- var oldFields = UserModel.cacheFields;
34
+ var oldFields = UserModel.dependencies;
35
35
 
36
+ UserModel.dependencies = ['userId', 'source'];
37
+
38
+ prefetch(getResources, expectedProps)(dummyEvt);
39
+ jest.advanceTimersByTime(100);
40
+
41
+ expect(Request.default.mock.calls[0][0]).toEqual('usersource=hbase_userId=noah');
42
+ expect(Request.default.mock.calls[0][1]).toEqual(UserModel);
43
+ expect(Request.default.mock.calls[0][2]).toEqual({
44
+ options: {userId: 'noah'},
45
+ params: {home: 'sf', source: 'hbase'},
46
+ prefetch: true
47
+ });
48
+
49
+ expect(Request.default.mock.calls[1][0]).toEqual('decisions');
50
+ expect(Request.default.mock.calls[1][1]).toEqual(DecisionsCollection);
51
+ expect(Request.default.mock.calls[1][2]).toEqual({prefetch: true});
52
+
53
+ expect(() => prefetch(() => false)({})).not.toThrow();
54
+ UserModel.dependencies = oldFields;
55
+ });
56
+
57
+ it('correctly turns the config object into cache key using legacy cacheFields', () => {
58
+ var oldFields = UserModel.dependencies;
59
+
60
+ UserModel.dependencies = [];
36
61
  UserModel.cacheFields = ['userId', 'source'];
37
62
 
38
63
  prefetch(getResources, expectedProps)(dummyEvt);
@@ -51,7 +76,8 @@ describe('prefetch', () => {
51
76
  expect(Request.default.mock.calls[1][2]).toEqual({prefetch: true});
52
77
 
53
78
  expect(() => prefetch(() => false)({})).not.toThrow();
54
- UserModel.cacheFields = oldFields;
79
+ UserModel.cacheFields = [];
80
+ UserModel.dependencies = oldFields;
55
81
  });
56
82
 
57
83
  it('will fire if the user hovers over the element for longer than the timeout', () => {