resourcerer 1.2.1 → 1.2.3

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
@@ -139,6 +139,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
139
139
  1. [prefetches](#prefetches)
140
140
  1. [data](#data)
141
141
  1. [lazy](#lazy)
142
+ 1. [minDuration](#minduration)
142
143
  1. [dependsOn](#dependson)
143
144
  1. [provides](#provides)
144
145
  1. [Data mutations](#data-mutations)
@@ -374,11 +375,11 @@ export default class UserModel extends Model {
374
375
  return `/users/${userId}`;
375
376
  }
376
377
 
377
- static cacheFields = ['userId']
378
+ static dependencies = ['userId'];
378
379
  }
379
380
  ```
380
381
 
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:
382
+ 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
383
 
383
384
  1. the `options` object
384
385
  1. the `data` object
@@ -422,7 +423,7 @@ In general, there are two ways to change `props.id` as in the previous example:
422
423
 
423
424
  ### params
424
425
 
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:
426
+ 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
427
 
427
428
  ```js
428
429
  @withResources((ResourceKeys, props) => {
@@ -442,14 +443,14 @@ The `params` option is passed directly to the [sync method](/docs/model.md#sync)
442
443
  class UserTodos extends React.Component {}
443
444
  ```
444
445
 
445
- Now, as the prop fields change, the params sent with the request changes as well (provided we set our `cacheFields` property accordingly):
446
+ Now, as the prop fields change, the params sent with the request changes as well (provided we set our `dependencies` property accordingly):
446
447
 
447
448
  `https://example.com/users/noahgrant/todos?limit=20&end_time=1494611831024&start_time=1492019831024&sort_field=importance`
448
449
 
449
450
 
450
451
  ### options
451
452
 
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:
453
+ [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
454
 
454
455
  ```js
455
456
  const getResources = (ResourceKeys, props) => {
@@ -469,7 +470,7 @@ const getResources = (ResourceKeys, props) => {
469
470
  };
470
471
  ```
471
472
 
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:
473
+ 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
474
 
474
475
  ```js
475
476
  // js/models/user_todos_collection.js
@@ -479,7 +480,7 @@ export class UserTodosCollection extends Collection {
479
480
  return `/users/${userId}/todos`;
480
481
  }
481
482
 
482
- static cacheFields = ['userId']
483
+ static dependencies = ['userId'];
483
484
  };
484
485
  ```
485
486
 
@@ -560,7 +561,7 @@ const getResources = (ResourceKeys, props) => {
560
561
 
561
562
  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
563
 
563
- 1. Don't forget to add `from` to the [`cacheFields`](#declarative-cache-keys) list!
564
+ 1. Don't forget to add `from` to the [`dependencies`](#declarative-cache-keys) list!
564
565
  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
566
 
566
567
  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 +583,7 @@ function MyCustomerComponent(props) {
582
583
 
583
584
  You can also use `data` to take advantage of [re-caching](/docs/advanced_topics.md#recaching-newly-saved-models).
584
585
 
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.
586
+ 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
587
 
587
588
  ### lazy
588
589
 
@@ -627,6 +628,10 @@ function TodoSearchItem(props) {
627
628
 
628
629
  If the todo model has been fetched already, we'll read straight from that. And if it gets updated, this component, via resourcerer, is listening for updates and will re-render to keep our entire UI in sync. Otherwise, we'll just fall back to our read-only search results. WIN!
629
630
 
631
+ ### minDuration
632
+
633
+ Sometimes requests can be _too_ fast for certain UIs. In these cases, spinners and other loading states can appear more like a jarring flicker than a helpful status indicator. For these, you can pass a `minDuration` equal to the minimum number of milliseconds that a request should take. This is great for [save and destroy](#data-mutations) requests. It will work for fetch requests via `useResources`, as well, but beware: if multiple components use the same resource and there are different (or missing) values for `minDuration`, this will cause a race condition.
634
+
630
635
  ### dependsOn
631
636
 
632
637
  See the section on [serial requests](#serial-requests).
@@ -812,7 +817,7 @@ Again, it’s unlikely that you’ll use `ModelCache` directly while using `reso
812
817
 
813
818
  ## Declarative Cache Keys
814
819
 
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:
820
+ 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
821
 
817
822
  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
823
 
@@ -847,18 +852,18 @@ export class UserTodosCollection extends Collection {
847
852
  }
848
853
  // ...
849
854
 
850
- static cacheFields = [
855
+ static dependencies = [
851
856
  'limit',
852
857
  'userId',
853
858
  'sort_field',
854
859
  ({end_millis, start_millis}) => ({range: end_millis - start_millis})
855
- ]
860
+ ];
856
861
  };
857
862
  ```
858
863
 
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.
864
+ 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
865
 
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.
866
+ 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
867
 
863
868
  The generated cache key would be something like `userTodos_limit=50_$range=86400000_sort_field=importance_userId=noah`. Again, note that:
864
869
 
@@ -930,10 +935,10 @@ import {Model} from 'resourcerer';
930
935
 
931
936
  class MyMeasuredModel extends Model {
932
937
  // either a boolean, which will track every request of this model instance
933
- static measure = true
938
+ static measure = true;
934
939
 
935
940
  // or a function that returns a boolean, which will track instance requests based on a condition
936
- static measure = ({data={}}) => data.id === 'noahgrant'
941
+ static measure = ({data={}}) => data.id === 'noahgrant';
937
942
  }
938
943
  ```
939
944
 
@@ -1051,7 +1056,7 @@ ResourcesConfig.set(configObj);
1051
1056
  // not component-specific, so they should be defined on the model instead of the component
1052
1057
  // todos-collection.js
1053
1058
  export default class TodosCollection extends Collection {
1054
- static cacheFields = ['category']
1059
+ static dependencies = ['category'];
1055
1060
 
1056
1061
  url() {
1057
1062
  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
@@ -13,6 +13,7 @@ declare module 'resourcerer' {
13
13
  method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
14
14
  params?: Record<string, any>;
15
15
  url?: string;
16
+ minDuration?: number;
16
17
  // they are free to add any other options they like
17
18
  [key: string]: any;
18
19
  };
@@ -74,6 +75,8 @@ declare module 'resourcerer' {
74
75
 
75
76
  static cacheFields: Array<string | ((attrs: T) => Record<string, any>)>;
76
77
 
78
+ static dependencies: Array<string | ((attrs: T) => Record<string, any>)>;
79
+
77
80
  static cacheTimeout: number;
78
81
 
79
82
  static idAttribute: string;
@@ -148,6 +151,8 @@ declare module 'resourcerer' {
148
151
 
149
152
  static cacheFields: Array<string | ((attrs: T) => Record<string, any>)>;
150
153
 
154
+ static dependencies: Array<string | ((attrs: T) => Record<string, any>)>;
155
+
151
156
  static modelIdAttribute: string;
152
157
 
153
158
  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
  /**
@@ -106,6 +106,7 @@ export const useResources = (getResources, props) => {
106
106
  // to keep track of which models have been updated in state, and then we'll reset this when
107
107
  // useEffect is finally called.
108
108
  cachedModelsSinceLastEffect = useRef({}),
109
+ refetchedModelsSinceLastEffect = useRef({}),
109
110
 
110
111
  forceUpdate = useForceUpdate(),
111
112
 
@@ -123,7 +124,13 @@ export const useResources = (getResources, props) => {
123
124
  previousCacheKey = prevConfig && getCacheKey(prevConfig);
124
125
 
125
126
  return (!previousCacheKey || previousCacheKey !== getCacheKey(config) ||
126
- !hasAllDependencies(prevPropsRef.current, [, config]) || config.refetch ||
127
+ !hasAllDependencies(prevPropsRef.current, [, config]) ||
128
+ // we only want to refetch if the resource is currently in a loaded state. but then
129
+ // we'll move to a loading state and short-circuit the render cycle, and it won't be
130
+ // loaded in the next cycle. that's why we use the ref, as well
131
+ (config.refetch &&
132
+ (hasLoaded(loadingStates[getResourceState(name)]) ||
133
+ refetchedModelsSinceLastEffect.current[name])) ||
127
134
  // make sure if we were lazy and are no longer lazy (from the same component) that we
128
135
  // get included in the list to get updated (and vice versa)
129
136
  (prevConfig?.lazy !== config.lazy));
@@ -202,6 +209,14 @@ export const useResources = (getResources, props) => {
202
209
  attachModelListeners();
203
210
  }
204
211
 
212
+ // register any refetched items in the ref so that when we short-circuit the render we still
213
+ // know which ones we need to fetch
214
+ resourcesToFetch.forEach(([name, config]) => {
215
+ if (config.refetch) {
216
+ refetchedModelsSinceLastEffect.current[name] = true;
217
+ }
218
+ });
219
+
205
220
  // set our updated resources' loading states to LOADING. but don't set if we're already in a
206
221
  // loading state for that resource, because that's a pointless extra render. also, any resources
207
222
  // that have lost their dependencies should go back to a pending state.
@@ -263,7 +278,7 @@ export const useResources = (getResources, props) => {
263
278
  onRequestFailure: (status, [name, config]) => {
264
279
  ReactDOM.unstable_batchedUpdates(() => {
265
280
  // request failed, which means this model should not be in the cache. but we still want
266
- // to // set our model state so that when we go back into a loading state, the empty
281
+ // to set our model state so that when we go back into a loading state, the empty
267
282
  // model is present instead of any previously-loaded model
268
283
  setModels(modelAggregator([[name, config]]));
269
284
 
@@ -281,8 +296,9 @@ export const useResources = (getResources, props) => {
281
296
  }
282
297
 
283
298
  prevPropsRef.current = props;
284
- // now we can reset this value
299
+ // now we can reset these values
285
300
  cachedModelsSinceLastEffect.current = {};
301
+ refetchedModelsSinceLastEffect.current = {};
286
302
  });
287
303
 
288
304
  // this effect attaches listeners to any bypassed models (ie, those passed in) which don't get
@@ -307,17 +323,6 @@ export const useResources = (getResources, props) => {
307
323
  };
308
324
  }, []);
309
325
 
310
- /**
311
- * This effect promptly removes any entries placed in the `refetches` resources state array.
312
- * Doing this here ensures that we don't have repeated effects with refetches, since that passes
313
- * them through the `resourcesToUpdate` path.
314
- */
315
- useEffect(() => {
316
- if ((props.refetches || []).length) {
317
- setResourceState(({refetches, ...state}) => state);
318
- }
319
- }, [(props.refetches || []).join()]);
320
-
321
326
  currentPropsRef.current = props;
322
327
 
323
328
  return {
@@ -331,11 +336,22 @@ export const useResources = (getResources, props) => {
331
336
  ...resourceState,
332
337
 
333
338
  refetch: (fn) => {
334
- var refetches = fn(ResourceKeys);
335
-
336
- if (refetches.length) {
337
- setResourceState((state) => ({...state, refetches}));
338
- }
339
+ ReactDOM.unstable_batchedUpdates(() => {
340
+ fn(ResourceKeys).forEach((name) => {
341
+ var model = getModelFromCache(
342
+ findConfig([name, {}], getResources, props)
343
+ );
344
+
345
+ /**
346
+ * Set a refetching flag on the model and re-render. This will cause all components
347
+ * that use this model to re-render and put it back in a loading state.
348
+ */
349
+ if (model) {
350
+ model.refetching = true;
351
+ model.triggerUpdate();
352
+ }
353
+ });
354
+ });
339
355
  },
340
356
 
341
357
  setResourceState,
@@ -397,7 +413,7 @@ function generateResources(getResources, props) {
397
413
  .reduce((memo, [name, config={}]) =>
398
414
  memo.concat([[name, {
399
415
  modelKey: config.modelKey || name,
400
- refetch: props.refetches?.includes(name),
416
+ refetch: !!getModelFromCache({...config, modelKey: config.modelKey || name})?.refetching,
401
417
  ...config
402
418
  }]].concat(
403
419
  // expand prefetched resources with their own options based on
@@ -474,21 +490,26 @@ function getEmptyModel({modelKey, data, options}) {
474
490
  /**
475
491
  * Calculates a cache key for the resource depending on the base resource type
476
492
  * key and the truthy parameter values. Parameter values are calculated in via
477
- * the constructor's static `cacheFields` array:
493
+ * the constructor's static `dependencies` array:
478
494
  *
479
- * `cacheFields` values are taken directly from the config object as opposed
495
+ * `dependencies` values are taken directly from the config object as opposed
480
496
  * to props, in the following order: `options` object, `data` object,
481
497
  * `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
498
+ * preferred. `dependencies` entries can be functions, too, which take the
483
499
  * `params` object as a parameter and return a key/value object that gets
484
500
  * flattened to a piece of the cache key.
485
501
  *
502
+ * We also support the deprecated `cacheFields` instead.
503
+ *
486
504
  * @param {object} config - resource config object (destructured)
487
505
  * @return {string} cache key
488
506
  */
489
507
  export function getCacheKey({modelKey, params={}, options={}, data={}}) {
490
508
  var toKeyValString = ([key, val]) => val ? `${key}=${val}` : '',
491
- fields = (ModelMap[modelKey]?.cacheFields || []).map(
509
+ dependencies = ModelMap[modelKey]?.dependencies?.length ?
510
+ ModelMap[modelKey].dependencies :
511
+ ModelMap[modelKey]?.cacheFields || [],
512
+ fields = dependencies.map(
492
513
  (key) => typeof key === 'function' ?
493
514
  Object.entries(key(params)).map(toKeyValString).join('_') :
494
515
  toKeyValString([key, options[key] || data[key] || params[key]])
@@ -893,6 +914,8 @@ function fetchResources(resources, props, {
893
914
  trackRequestTime(name, config);
894
915
  }
895
916
 
917
+ delete model.refetching;
918
+
896
919
  // add unfetched resources that a model might provide
897
920
  if (ModelMap[modelKey].providesModels) {
898
921
  ModelMap[modelKey].providesModels(model, ResourceKeys).forEach((uConfig) => {
@@ -924,6 +947,10 @@ function fetchResources(resources, props, {
924
947
 
925
948
  // error callback
926
949
  (status) => {
950
+ // if a refetching request errors, we still want to remove the refetching flag
951
+ // before going into an error state
952
+ delete getModelFromCache(config)?.refetching;
953
+
927
954
  // this catch block gets called _only_ for request errors.
928
955
  // don't set error state unless resource is current
929
956
  if (isCurrentResource([name, config], cacheKey)) {
package/lib/sync.js CHANGED
@@ -50,7 +50,24 @@ export default function(model, options={}) {
50
50
  */
51
51
  export function ajax(options) {
52
52
  var hasParams = !!Object.keys(options.params || {}).length,
53
- hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasParams;
53
+ hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasParams,
54
+ startTime = Date.now(),
55
+ onRequestComplete = (json, response) => {
56
+ var requestDuration = Date.now() - startTime,
57
+ routeRequest = (
58
+ resolve=Promise.resolve.bind(Promise),
59
+ reject=Promise.reject.bind(Promise)
60
+ ) => response.ok ?
61
+ resolve([json, response]) :
62
+ reject(Object.assign(response, {json}));
63
+
64
+ return !options.minDuration || requestDuration >= options.minDuration ?
65
+ routeRequest() :
66
+ new Promise((resolve, reject) => window.setTimeout(
67
+ () => routeRequest(resolve, reject),
68
+ options.minDuration - requestDuration
69
+ ));
70
+ };
54
71
 
55
72
  if (options.method === 'GET' && hasParams) {
56
73
  options.url += (options.url.indexOf('?') > -1 ? '&' : '?') +
@@ -80,7 +97,7 @@ export function ajax(options) {
80
97
  }).then(
81
98
  (res) => res.json()
82
99
  .catch(() => ({}))
83
- .then((json) => res.ok ? [json, res] : Promise.reject(Object.assign(res, {json})))
100
+ .then((json) => onRequestComplete(json, res))
84
101
  ).catch(options.error);
85
102
  }
86
103
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "1.2.1",
3
+ "version": "1.2.3",
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', () => {
package/test/sync.test.js CHANGED
@@ -227,6 +227,18 @@ describe('sync', () => {
227
227
  }
228
228
  });
229
229
 
230
+ it('waits minDuration to resolve if one is passed', async() => {
231
+ var resolved;
232
+
233
+ library.fetch({minDuration: 150}).then(() => resolved = true);
234
+ await new Promise((res) => window.setTimeout(res, 50));
235
+ expect(resolved).not.toBeDefined();
236
+ await new Promise((res) => window.setTimeout(res, 50));
237
+ expect(resolved).not.toBeDefined();
238
+ await new Promise((res) => window.setTimeout(res, 50));
239
+ expect(resolved).toBe(true);
240
+ });
241
+
230
242
  describe('headers', () => {
231
243
  it('can override contentType in options', async() => {
232
244
  setRequestPrefilter((options) => ({