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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -130,22 +130,24 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
130
130
  1. [Other Props Returned from the Hook/Passed from the HOC (Loading States)](other-props-returned-from-the-hookpassed-from-the-hoc-loading-states)
131
131
  1. [Requesting Prop-driven Data](#requesting-prop-driven-data)
132
132
  1. [Changing Props](#changing-props)
133
- 1. [Serial Requests](#serial-requests)
134
- 1. [Other Common Resource Config Options](#other-common-resource-config-options)
135
- 1. [data](#data)
133
+ 1. [Common Resource Config Options](#common-resource-config-options)
134
+ 1. [params](#params)
136
135
  1. [options](#options)
137
136
  1. [noncritical](#noncritical)
138
137
  1. [forceFetch](#forcefetch)
139
138
  1. [Custom Resource Names](#custom-resource-names)
140
139
  1. [prefetches](#prefetches)
141
- 1. [attributes](#attributes)
140
+ 1. [data](#data)
141
+ 1. [dependsOn](#dependson)
142
+ 1. [provides](#provides)
142
143
  1. [Data mutations](#data-mutations)
143
- 1. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
144
- 1. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
145
- 1. [Declarative Cache Keys](#declarative-cache-keys)
146
- 1. [Prefetch on Hover](#prefetch-on-hover)
147
- 1. [Refetching](#refetching)
148
- 1. [Tracking Request Times](#tracking-request-times)
144
+ 1. [Serial Requests](#serial-requests)
145
+ 3. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
146
+ 4. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
147
+ 5. [Declarative Cache Keys](#declarative-cache-keys)
148
+ 6. [Prefetch on Hover](#prefetch-on-hover)
149
+ 7. [Refetching](#refetching)
150
+ 8. [Tracking Request Times](#tracking-request-times)
149
151
  1. [Configuring resourcerer](#configuring-resourcerer)
150
152
  1. [FAQs](#faqs)
151
153
 
@@ -190,7 +192,7 @@ module: {
190
192
 
191
193
  return {
192
194
  [USER_TODOS]: {
193
- data: {
195
+ params: {
194
196
  limit: 20,
195
197
  end_time: now,
196
198
  start_time: now - props.timeRange,
@@ -364,12 +366,10 @@ And here's what our model might look like:
364
366
  import {Model} from 'resourcerer';
365
367
 
366
368
  export default class UserModel extends Model {
367
- constructor(attributes, options={}) {
368
- this.userId = options.userId;
369
- }
370
-
371
- url() {
372
- return `/users/${this.userId}`;
369
+ url({userId}) {
370
+ // `userId` is passed in here because we have
371
+ // `options: {userId: props.userId}` in the resource config object
372
+ return `/users/${userId}`;
373
373
  }
374
374
 
375
375
  static cacheFields = ['userId']
@@ -378,9 +378,9 @@ export default class UserModel extends Model {
378
378
 
379
379
  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:
380
380
 
381
- 1. the `options` object a model/collection is initialized with
382
- 1. the `attributes` object a model is initialized with
383
- 1. the `data` a model/collection gets passed in a fetch
381
+ 1. the `options` object
382
+ 1. the `data` object
383
+ 1. the `params` object
384
384
 
385
385
  All three of these come from via the [Resource Configuration Object](#nomenclature) that is returned from our executor function; it might look like this:
386
386
 
@@ -415,71 +415,12 @@ In general, there are two ways to change `props.id` as in the previous example:
415
415
  Note that `setResourceState` is very useful for the `withResources` HOC because it allows you to 'lift' state above the fetching component that otherwise would not be possible. For `useResources`, it is a nice-to-have in some cases, but because you can always define your own `useState` above the `useResources` invocation, you may find that you use it less often.
416
416
 
417
417
 
418
- ## Serial Requests
419
418
 
420
- In most situations, all resource requests should be parallelized; but that’s not always possible. Every so often, there may be a situation where one request depends on the result of another. For these cases, we have the `dependsOn` resource config option and the `provides` resource config option. These are probably best explained by example, so here is a simplified instance from the [Sift](https://sift.com) Console, where we load a queue item that has info about a user, but we can't get further user information until we know what user id belongs to this queue item.
419
+ ## Common Resource Config Options
421
420
 
422
- ```js
423
- @withResources(({QUEUE_ITEM, USER}, props) => ({
424
- [USER]: {
425
- options: {userId: props.userId},
426
- dependsOn: ['userId']
427
- },
428
- [QUEUE_ITEM]: {
429
- attributes: {id: props.itemId}
430
- provides: {userId: getUserIdFromItem}
431
- }
432
- }))
433
- export default class QueueItemPage extends React.Component {}
434
-
435
- function getUserIdFromItem(queueItemModel) {
436
- return queueItemModel.get('userId');
437
- }
438
- ```
439
-
440
- In this simplified example, only `props.itemId` is initially present at the url `items/<itemId>`, and since the UserModel depends on `props.userId` being present, that model won’t initially get fetched. Only the QueueItemModel gets fetched at first; it has the `provides` option, which is a map of `<string: function>`, where the string is the prop that it provides to the HOC wrapper, and the function is a private static ‘transform’ function&mdash;it takes its model as an argument and returns the value for the prop it provides.
441
-
442
- So, in this case, `getUserIdFromItem` is the transform function, which takes the `queueItemModel` as an argument and returns the userId that will be assigned to `props.userId` (or, more accurately, will be set as state via `setResourceState` as described in the previous section). When the QueueItemModel resource returns, the transform function is invoked; at that point, `props.userId` exists, and the UserModel will be fetched. And we have serially requested our resources!
421
+ ### params
443
422
 
444
- One thing to note here is that while the `QUEUE_ITEM` resource is being fetched, the user resource is in a `PENDING` state, which is a special state that does not contribute to overall component `isLoading`/`hasErrored` states (though it will keep the component from being `hasLoaded`). At this point, the `QueueItemPage` in the example above is in a `LOADING` state (`isLoading === true`) because `QUEUE_ITEM` is loading. When it returns with the user id, the `USER` resource is put into a `LOADING` state, and the component then remains `isLoading === true` until it returns, after which the component has successfully loaded. If the `QUEUE_ITEM` resource happened to error, for some reason, the `USER` resource would never get out of its `PENDING` state, and the component would then take on the `ERROR` state (`hasErrored === true`) of `QUEUE_ITEM`. For more on `PENDING`, see [Thoughts on the PENDING State](/docs/advanced_topics.md#thoughts-on-the-pending-resource) in the [Advanced Topics document](/docs/advanced_topics.md).
445
-
446
- Finally, if a model is to provide more than a single prop, use an underscore instead of the prop name in the `provides` object. Instead of the transform function returning the prop value, it should then return an object of prop keys and values, which will get spread to the component:
447
-
448
- ```js
449
- const getResources = ({QUEUE_ITEM, USER}, props) => ({
450
- [USER]: {
451
- options: {state: props.activeState, userId: props.userId},
452
- // userModel depends on multiple props from queueItemModel
453
- dependsOn: ['activeState', 'userId']
454
- },
455
- [QUEUE_ITEM]: {
456
- attributes: {id: props.itemId}
457
- // use an underscore here to tell resourcerer to spread the resulting object
458
- provides: {_: getUserDataFromItem}
459
- }
460
- });
461
-
462
- export default function QueueItemPage(props) {
463
- // activeState and userId are internal state within `useResources` and returned
464
- var {
465
- activeState,
466
- userId,
467
- userModel,
468
- queueItemModel
469
- } = useResources(getResources, props);
470
- }
471
-
472
- function getUserDataFromItem(queueItemModel) {
473
- // transform function now returns an object of prop names/values instead of a simple prop value
474
- return {userId: queueItemModel.get('userId'), activeState: queueItemModel.get('state')};
475
- }
476
- ```
477
-
478
- ## Other Common Resource Config Options
479
-
480
- ### data
481
-
482
- The `data` 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 `data` property:
423
+ 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:
483
424
 
484
425
  ```js
485
426
  @withResources((ResourceKeys, props) => {
@@ -487,7 +428,7 @@ The `data` option is passed directly to the [sync method](/docs/model.md#sync) a
487
428
 
488
429
  return {
489
430
  [ResourceKeys.USER_TODOS]: {
490
- data: {
431
+ params: {
491
432
  limit: 20,
492
433
  end_time: now,
493
434
  start_time: now - props.timeRange,
@@ -499,13 +440,14 @@ The `data` option is passed directly to the [sync method](/docs/model.md#sync) a
499
440
  class UserTodos extends React.Component {}
500
441
  ```
501
442
 
502
- Now, as the prop fields change, the data sent with the request changes as well (provided we set our `cacheFields` property accordingly):
443
+ Now, as the prop fields change, the params sent with the request changes as well (provided we set our `cacheFields` property accordingly):
503
444
 
504
445
  `https://example.com/users/noahgrant/todos?limit=20&end_time=1494611831024&start_time=1492019831024&sort_field=importance`
505
446
 
506
- ### options
507
447
 
508
- [As referenced previously](#requesting-prop-driven-data), an `options` hash on a resource config will be passed directly as the second parameter to a model's `constructor` method. 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:
448
+ ### options
449
+
450
+ [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:
509
451
 
510
452
  ```js
511
453
  const getResources = (ResourceKeys, props) => {
@@ -513,7 +455,7 @@ const getResources = (ResourceKeys, props) => {
513
455
 
514
456
  return {
515
457
  [ResourceKeys.USER_TODOS]: {
516
- data: {
458
+ params: {
517
459
  limit: 20,
518
460
  end_time: now,
519
461
  start_time: now - props.timeRange,
@@ -525,7 +467,19 @@ const getResources = (ResourceKeys, props) => {
525
467
  };
526
468
  ```
527
469
 
528
- Here, the UserTodos collection will be instantiated with an options hash including the `userId` property, which it uses to construct its url. 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. Whereas the [`data` object](#data) is the place to add query param data (GET) or body data (POST/PUT/PATCH), the `options` object is a great place to add _path param_ data, as in this UserModel example's url (`/users/${this.userId}`).
470
+ 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:
471
+
472
+ ```js
473
+ // js/models/user_todos_collection.js
474
+ export class UserTodosCollection extends Collection {
475
+ url({userId}) {
476
+ // userId gets passed in for us to help construct our url
477
+ return `/users/${userId}/todos`;
478
+ }
479
+
480
+ static cacheFields = ['userId']
481
+ };
482
+ ```
529
483
 
530
484
 
531
485
  ### noncritical
@@ -579,7 +533,7 @@ const getResources = (ResourceKeys, props) => {
579
533
 
580
534
  return {
581
535
  [ResourceKeys.USER_TODOS]: {
582
- data: {
536
+ params: {
583
537
  from: props.page * REQUESTS_PER_PAGE,
584
538
  limit: REQUESTS_PER_PAGE,
585
539
  end_time: now,
@@ -604,9 +558,32 @@ When the user clicks on a 'next' arrow that updates page state, the collection w
604
558
 
605
559
  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.
606
560
 
607
- ### attributes
561
+ ### data
562
+
563
+ Pass in a data hash to initialize a Model instance with data before initially fetching. This is passed directly to the [model](/docs/model.md#constructor) `constructor` method, and is typically much less useful than providing the properties directly to the [`params`](#params) property. One place it might be useful is to seed a model with an id you already have:
564
+
565
+ ```js
566
+ getResources = ({CUSTOMER}) => ({[CUSTOMER]: {data: {id: props.customerId}}});
567
+
568
+ function MyCustomerComponent(props) {
569
+ var {customerModel} = useResources(getResources, props);
570
+
571
+ // now you can reference the id directly on the model
572
+ console.log(customerModel.get('id')); // or the id shorthand, customerModel.id
573
+ }
574
+ ```
575
+
576
+ You can also use `data` to take advantage of [re-caching](/docs/advanced_topics.md#recaching-newly-saved-models).
577
+
578
+ 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.
608
579
 
609
- Pass in an attributes hash to initialize a Model instance with a body before initially fetching. This is passed directly to the [model](/docs/model.md#constructor) `constructor` method along with the [`options`](#options) property, and is typically much less useful than providing the properties directly to the [`data`](#data) property. Like `data` and `options`, the `attributes` 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.
580
+ ### dependsOn
581
+
582
+ See the section on [serial requests](#serial-requests).
583
+
584
+ ### provides
585
+
586
+ See the section on [serial requests](#serial-requests).
610
587
 
611
588
  # Data Mutations
612
589
 
@@ -679,7 +656,67 @@ Each one of these methods exhibit the following behaviors:
679
656
  **Note:**
680
657
  1. All calls resolve an array, which is a tuple of [model, response]. All reject with just the response.
681
658
  1. All write calls must have a `.catch` attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.
659
+ 2.
660
+
661
+ ## Serial Requests
682
662
 
663
+ In most situations, all resource requests should be parallelized; but that’s not always possible. Every so often, there may be a situation where one request depends on the result of another. For these cases, we have the `dependsOn` resource config option and the `provides` resource config option. These are probably best explained by example, so here is a simplified instance from the [Sift](https://sift.com) Console, where we load a queue item that has info about a user, but we can't get further user information until we know what user id belongs to this queue item.
664
+
665
+ ```js
666
+ @withResources(({QUEUE_ITEM, USER}, props) => ({
667
+ [USER]: {
668
+ options: {userId: props.userId},
669
+ dependsOn: ['userId']
670
+ },
671
+ [QUEUE_ITEM]: {
672
+ data: {id: props.itemId}
673
+ provides: {userId: getUserIdFromItem}
674
+ }
675
+ }))
676
+ export default class QueueItemPage extends React.Component {}
677
+
678
+ function getUserIdFromItem(queueItemModel) {
679
+ return queueItemModel.get('userId');
680
+ }
681
+ ```
682
+
683
+ In this simplified example, only `props.itemId` is initially present at the url `items/<itemId>`, and since the UserModel depends on `props.userId` being present, that model won’t initially get fetched. Only the QueueItemModel gets fetched at first; it has the `provides` option, which is a map of `<string: function>`, where the string is the prop that it provides to the HOC wrapper, and the function is a private static ‘transform’ function&mdash;it takes its model as an argument and returns the value for the prop it provides.
684
+
685
+ So, in this case, `getUserIdFromItem` is the transform function, which takes the `queueItemModel` as an argument and returns the userId that will be assigned to `props.userId` (or, more accurately, will be set as state via `setResourceState` as described in the previous section). When the QueueItemModel resource returns, the transform function is invoked; at that point, `props.userId` exists, and the UserModel will be fetched. And we have serially requested our resources!
686
+
687
+ One thing to note here is that while the `QUEUE_ITEM` resource is being fetched, the user resource is in a `PENDING` state, which is a special state that does not contribute to overall component `isLoading`/`hasErrored` states (though it will keep the component from being `hasLoaded`). At this point, the `QueueItemPage` in the example above is in a `LOADING` state (`isLoading === true`) because `QUEUE_ITEM` is loading. When it returns with the user id, the `USER` resource is put into a `LOADING` state, and the component then remains `isLoading === true` until it returns, after which the component has successfully loaded. If the `QUEUE_ITEM` resource happened to error, for some reason, the `USER` resource would never get out of its `PENDING` state, and the component would then take on the `ERROR` state (`hasErrored === true`) of `QUEUE_ITEM`. For more on `PENDING`, see [Thoughts on the PENDING State](/docs/advanced_topics.md#thoughts-on-the-pending-resource) in the [Advanced Topics document](/docs/advanced_topics.md).
688
+
689
+ Finally, if a model is to provide more than a single prop, use an underscore instead of the prop name in the `provides` object. Instead of the transform function returning the prop value, it should then return an object of prop keys and values, which will get spread to the component:
690
+
691
+ ```js
692
+ const getResources = ({QUEUE_ITEM, USER}, props) => ({
693
+ [USER]: {
694
+ options: {state: props.activeState, userId: props.userId},
695
+ // userModel depends on multiple props from queueItemModel
696
+ dependsOn: ['activeState', 'userId']
697
+ },
698
+ [QUEUE_ITEM]: {
699
+ data: {id: props.itemId}
700
+ // use an underscore here to tell resourcerer to spread the resulting object
701
+ provides: {_: getUserDataFromItem}
702
+ }
703
+ });
704
+
705
+ export default function QueueItemPage(props) {
706
+ // activeState and userId are internal state within `useResources` and returned
707
+ var {
708
+ activeState,
709
+ userId,
710
+ userModel,
711
+ queueItemModel
712
+ } = useResources(getResources, props);
713
+ }
714
+
715
+ function getUserDataFromItem(queueItemModel) {
716
+ // transform function now returns an object of prop names/values instead of a simple prop value
717
+ return {userId: queueItemModel.get('userId'), activeState: queueItemModel.get('state')};
718
+ }
719
+ ```
683
720
 
684
721
  # Differences between useResources and withResources
685
722
 
@@ -691,7 +728,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
691
728
 
692
729
  ```js
693
730
  function MyComponent({start_time, ...props}) {
694
- var {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {data: {start_time}}}), props);
731
+ var {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {params: {start_time}}}), props);
695
732
 
696
733
  // ...
697
734
  ```
@@ -700,7 +737,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
700
737
 
701
738
  ```js
702
739
  function MyComponent(props) {
703
- var {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}}), props);
740
+ var {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
704
741
 
705
742
  // ...
706
743
  ```
@@ -708,7 +745,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
708
745
  or, even clearer, define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
709
746
 
710
747
  ```js
711
- const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}});
748
+ const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}});
712
749
 
713
750
  function MyComponent(props) {
714
751
  var {todosCollection} = useResources(getResources, props);
@@ -728,7 +765,7 @@ Again, it’s unlikely that you’ll use `ModelCache` directly while using `reso
728
765
 
729
766
  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:
730
767
 
731
- 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 [attributes](#attributes) hash, or the [data](#data) hash, in that order.
768
+ 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.
732
769
 
733
770
  2. A function, whose return value is an object of keys and values that should both contribute to the cache key.
734
771
 
@@ -740,7 +777,7 @@ const getResources = (ResourceKeys, props) => {
740
777
 
741
778
  return {
742
779
  [ResourceKeys.USER_TODOS]: {
743
- data: {
780
+ params: {
744
781
  limit: props.limit,
745
782
  end_time: now,
746
783
  start_time: now - props.timeRange,
@@ -756,12 +793,8 @@ And our corresponding model definition might look like this:
756
793
 
757
794
  ```js
758
795
  export class UserTodosCollection extends Collection {
759
- constructor(models, options={}) {
760
- this.userId = options.userId;
761
- }
762
-
763
- url() {
764
- return `/users/${this.userId}/todos`;
796
+ url({userId}) {
797
+ return `/users/${userId}/todos`;
765
798
  }
766
799
  // ...
767
800
 
@@ -774,15 +807,15 @@ export class UserTodosCollection extends Collection {
774
807
  };
775
808
  ```
776
809
 
777
- We can see that `limit` and `sort_field` as specified in `cacheFields` are taken straight from the `data` 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 `data` 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.
810
+ 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.
778
811
 
779
- The time range is a little tougher to cache, though. We're less interested the spcecific `end_time`/`start_time` values to the millisecond&mdash;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 `data` 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.
812
+ The time range is a little tougher to cache, though. We're less interested the spcecific `end_time`/`start_time` values to the millisecond&mdash;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.
780
813
 
781
814
  The generated cache key would be something like `userTodos_limit=50_$range=86400000_sort_field=importance_userId=noah`. Again, note that:
782
815
 
783
816
  - the `userId` value is taken from the `options` hash
784
- - the `limit` and `sort_field` values are taken from the `data` hash
785
- - the `range` value is taken from a function that takes `start_millis`/`end_millis` from the `data` hash into account.
817
+ - the `limit` and `sort_field` values are taken from the `params` hash
818
+ - the `range` value is taken from a function that takes `start_millis`/`end_millis` from the `params` hash into account.
786
819
 
787
820
 
788
821
  ## Prefetch on Hover
@@ -798,7 +831,7 @@ const getTodos = (ResourceKeys, props) => {
798
831
 
799
832
  return {
800
833
  [ResourceKeys.USER_TODOS]: {
801
- data: {
834
+ params: {
802
835
  limit: props.limit,
803
836
  end_time: now,
804
837
  start_time: now - props.timeRange,
@@ -828,7 +861,7 @@ It takes a function that is passed `ResourceKeys` and should return a list of `R
828
861
 
829
862
  ```js
830
863
  function MyComponent(props) {
831
- var {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}}), props);
864
+ var {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
832
865
 
833
866
  // ...
834
867
 
@@ -851,7 +884,7 @@ class MyMeasuredModel extends Model {
851
884
  static measure = true
852
885
 
853
886
  // or a function that returns a boolean, which will track instance requests based on a condition
854
- static measure = ({attributes={}}) => attributes.id === 'noahgrant'
887
+ static measure = ({data={}}) => data.id === 'noahgrant'
855
888
  }
856
889
  ```
857
890
 
@@ -910,10 +943,10 @@ ResourcesConfig.set(configObj);
910
943
  import {stringify} from 'qs';
911
944
 
912
945
  ResourcesConfig.set({
913
- stringify(data, options) {
914
- // data is the data object to be stringified into query parameters
946
+ stringify(params, options) {
947
+ // params is the params object to be stringified into query parameters
915
948
  // options is the request options object
916
- return stringify(data);
949
+ return stringify(params);
917
950
  }
918
951
  });
919
952
  ```
@@ -925,7 +958,7 @@ ResourcesConfig.set(configObj);
925
958
  * the event string, `'API Fetch'`
926
959
  * event data object with the following properties:
927
960
  * Resource (string): the name of the resource (taken from the entry in `ResourceKeys`)
928
- * data (object): data object supplied via the resource's config
961
+ * params (object): params object supplied via the resource's config
929
962
  * options (object): options object supplied via the resource's config
930
963
  * duration (number): time in milliseconds between request and response
931
964
 
@@ -1030,7 +1063,7 @@ ResourcesConfig.set(configObj);
1030
1063
 
1031
1064
  return {
1032
1065
  [ResourceKeys.USER_TODOS]: {
1033
- data: {
1066
+ params: {
1034
1067
  limit: 20,
1035
1068
  end_time: now,
1036
1069
  start_time: now - props.timeRange,
@@ -1046,7 +1079,7 @@ ResourcesConfig.set(configObj);
1046
1079
 
1047
1080
  * Can `resourcerer` do anything other than `GET` requests?
1048
1081
 
1049
- `resourcerer` only handles resource _fetching_ (i.e. calling [Model.prototype.fetch](/docs/model.md#fetch)). Note that this is not the same as only making `GET` requests; pass in a `method: 'POST'` property in a resource's config to turn the `data` property into a POST body, for example, when making a search request.
1082
+ `resourcerer` only handles resource _fetching_ (i.e. calling [Model.prototype.fetch](/docs/model.md#fetch)). Note that this is not the same as only making `GET` requests; pass in a `method: 'POST'` property in a resource's config to turn the `params` property into a POST body, for example, when making a search request.
1050
1083
 
1051
1084
  For write operations, use Models' [`save`](/docs/model.md#save) and [`destroy`](/docs/model.md#destroy) methods directly:
1052
1085
 
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
- * * model {Model} - dynamically overrides the static model property for the type of Model that
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
+ const RESERVED_OPTION_KEYS = ['Model', 'comparator', 'silent', 'parse'];
32
+
31
33
  this.Model = options.Model || this.constructor.Model;
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
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} data - request data
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(data, options) {
114
- return new URLSearchParams(data).toString();
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') || urlError();
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
- * * attributes {object} - attributes to pass a Model instance
39
- * * data {object} - data to pass into the fetch method
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
- attributes: {},
56
- data: {},
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[getFirstArgPropertyName(Model)], options.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({data: options.data}).then(
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
- }
@@ -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
- * * data {object} - data for the fetch call passed to the `request`
37
- * * options {object} - options object passed to the model's `initialize`
36
+ * * params {object} - query params for the fetch call passed to the `request`
37
+ * * options {object} - instance properties set on the model (which are not data)
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 [_resourceState, setResourceState] = useState({}),
60
- props = {...props, ..._resourceState},
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.attributes && !prevConfig.attributes?.id && config.attributes?.id) {
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
- ..._resourceState,
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, attributes, models, options}) {
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, `attributes` object,
434
- * `data` object. Field keys are included in this method, which is why it is
430
+ * to props, in the following order: `options` object, `data` object,
431
+ * `params` object. Field keys are included in this method, which is why it is
435
432
  * preferred. `cacheFields` entries can be functions, too, which take the
436
- * `data` object as a parameter and return a key/value object that gets
433
+ * `params` object as a parameter and return a key/value object that gets
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, data={}, options={}, attributes={}}) {
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(data)).map(toKeyValString).join('_') :
447
- toKeyValString([key, options[key] || attributes[key] || data[key]])
443
+ Object.entries(key(params)).map(toKeyValString).join('_') :
444
+ toKeyValString([key, options[key] || data[key] || params[key]])
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 no longer uses props directly, which
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<data: object, options: object>} fetch data and options
621
+ * @param {object<params: object, options: object>} fetch params and props
625
622
  */
626
- function trackRequestTime(name, {data, options}) {
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
- data,
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 {data, modelKey, provides={}, refetch, ...rest} = config,
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
- data,
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.models || uConfig.attributes) :
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 data if not explicitly specified
12
- * already. It also finds the base url or throws if one does not exist.
11
+ * ajax function. It basically sets up defaults, seeding the query params if not explicitly
12
+ * specified already. It also finds the base url or throws if one does not exist.
13
13
  *
14
14
  * @param {Model|Collection} model - model making API request
15
15
  * @param {object} options - generic map of request options
@@ -20,9 +20,9 @@ export default function(model, options={}) {
20
20
  return ajax({
21
21
  contentType: MIME_TYPE_JSON,
22
22
  // url can be passed via the model (as a property or function) or via options.url directly
23
- ...!options.url ? {url: result(model, 'url') || urlError()} : {},
24
- ...!options.data && ['POST', 'PATCH', 'PUT'].includes(options.method) ?
25
- {data: options.attrs || model.toJSON()} :
23
+ ...!options.url ? {url: result(model, 'url', model.urlOptions) || urlError()} : {},
24
+ ...!options.params && ['POST', 'PATCH', 'PUT'].includes(options.method) ?
25
+ {params: options.attrs || model.toJSON()} :
26
26
  {},
27
27
  // default catch block. most large applications should override this in the config settings to
28
28
  // provide support for things like 401s or 429s.
@@ -38,7 +38,8 @@ export default function(model, options={}) {
38
38
  * @param {object} options - map of request options:
39
39
  * * url {string} - this is required, but will be present automatically if not passed directly in
40
40
  * the sync method's request object
41
- * * data {object} - will be url-stringified for GET requests and JSON-stringified for POST bodies
41
+ * * params {object} - will be url-stringified for GET requests and JSON-stringified for POST
42
+ * bodies
42
43
  * * headers {object} - map of headers to their values
43
44
  * * contentType {string} value of content type header, which will also determine how the POST
44
45
  * bodies are assembled
@@ -48,12 +49,12 @@ export default function(model, options={}) {
48
49
  * rejects with the response
49
50
  */
50
51
  export function ajax(options) {
51
- var hasData = !!Object.keys(options.data || {}).length,
52
- hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasData;
52
+ var hasParams = !!Object.keys(options.params || {}).length,
53
+ hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method) && hasParams;
53
54
 
54
- if (options.method === 'GET' && hasData) {
55
+ if (options.method === 'GET' && hasParams) {
55
56
  options.url += (options.url.indexOf('?') > -1 ? '&' : '?') +
56
- ResourcesConfig.stringify(options.data, options);
57
+ ResourcesConfig.stringify(options.params, options);
57
58
  }
58
59
 
59
60
  options = {...options, ...prefilter(options)};
@@ -62,17 +63,17 @@ export function ajax(options) {
62
63
  ...options,
63
64
  headers: {
64
65
  Accept: MIME_TYPE_JSON,
65
- // only set contentType header if a write request and if there is body data. also, default to
66
- // JSON contentTypes, but allow for it to be overridden, ie with x-www-form-urlencoded.
66
+ // only set contentType header if a write request and if there is body params. also, default
67
+ // to JSON contentTypes, but allow for it to be overridden, ie with x-www-form-urlencoded.
67
68
  ...hasBodyContent ? {'Content-Type': options.contentType} : {},
68
69
  ...options.headers
69
70
  },
70
71
  ...hasBodyContent ? {
71
- body: typeof options.data === 'string' ?
72
- options.data :
72
+ body: typeof options.params === 'string' ?
73
+ options.params :
73
74
  options.contentType === MIME_TYPE_JSON ?
74
- JSON.stringify(options.data) :
75
- ResourcesConfig.stringify(options.data, options)
75
+ JSON.stringify(options.params) :
76
+ ResourcesConfig.stringify(options.params, options)
76
77
  } : {}
77
78
  // catch block here handles the case where the response isn't valid json,
78
79
  // like for example a 204 no content
package/lib/utils.js CHANGED
@@ -215,6 +215,6 @@ export function sortBy(list=[], comparator) {
215
215
  * @param {any} prop - property of object to evaluate
216
216
  * @return {any} evaluated value of object at property
217
217
  */
218
- export function result(obj={}, prop) {
219
- return typeof obj[prop] === 'function' ? obj[prop]() : obj[prop];
218
+ export function result(obj={}, prop, ...args) {
219
+ return typeof obj[prop] === 'function' ? obj[prop](...args) : obj[prop];
220
220
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "1.0.0-beta-3",
3
+ "version": "1.0.0-beta-4",
4
4
  "repository": "github.com/noahgrant/resourcerer",
5
5
  "description": "Declarative data-fetching and caching framework for React",
6
6
  "keywords": [
@@ -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;
@@ -4,11 +4,10 @@ import Model from '../lib/model';
4
4
  export class UserModel extends Model {
5
5
  key = 'user'
6
6
 
7
- constructor(attrs, options={}) {
8
- super(attrs, options);
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
- constructor(attributes, options={}) {
43
- super(attributes, options);
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
- data: JSON.stringify(options.data),
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
- constructor(attrs, options={}) {
121
- super(attrs, options);
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
  }
@@ -64,6 +64,12 @@ describe('Model', () => {
64
64
  expect(model.toJSON()).toEqual({});
65
65
  });
66
66
 
67
+ it('unreserved option items are assigned to a `urlOptions` instance property', () => {
68
+ model = new Model({}, {one: 1, two: 2, parse: true, silent: true});
69
+
70
+ expect(model.urlOptions).toEqual({one: 1, two: 2});
71
+ });
72
+
67
73
  it('can optionally have defaults that are a function', () => {
68
74
  class _Model extends Model {
69
75
  static defaults = {one: 1, two: 2}
@@ -470,6 +476,22 @@ describe('Model', () => {
470
476
  model = new _Model({name: 'noah?grant'}, {collection});
471
477
  expect(model.url()).toEqual('/library/noah%3Fgrant');
472
478
  });
479
+
480
+ it('is called by default with its urlOptions', () => {
481
+ class _Model extends Model {
482
+ urlRoot({section}) {
483
+ return `/library/${section}`;
484
+ }
485
+ }
486
+
487
+ model = new _Model({}, {section: 'nature'});
488
+ expect(model.url()).toEqual('/library/nature');
489
+
490
+ collection = new Collection();
491
+ collection.url = ({section}) => `/library/${section}`;
492
+ model = new Model({}, {collection, section: 'history'});
493
+ expect(model.url()).toEqual('/library/history');
494
+ });
473
495
  });
474
496
 
475
497
  describe('parse', () => {
@@ -8,7 +8,7 @@ import ReactDOM from 'react-dom';
8
8
  const renderNode = document.createElement('div');
9
9
  const getResources = ({DECISIONS, USER}, props) => ({
10
10
  [USER]: {
11
- data: {home: props.home, source: props.source},
11
+ params: {home: props.home, source: props.source},
12
12
  options: {userId: props.userId}
13
13
  },
14
14
  [DECISIONS]: {}
@@ -30,7 +30,7 @@ describe('prefetch', () => {
30
30
  jest.useRealTimers();
31
31
  });
32
32
 
33
- it('correctly turns the config object into cache key, data, and options', () => {
33
+ it('correctly turns the config object into cache key, params, and options', () => {
34
34
  var oldFields = UserModel.cacheFields;
35
35
 
36
36
  UserModel.cacheFields = ['userId', 'source'];
@@ -42,7 +42,7 @@ describe('prefetch', () => {
42
42
  expect(Request.default.mock.calls[0][1]).toEqual(UserModel);
43
43
  expect(Request.default.mock.calls[0][2]).toEqual({
44
44
  options: {userId: 'noah'},
45
- data: {home: 'sf', source: 'hbase'},
45
+ params: {home: 'sf', source: 'hbase'},
46
46
  prefetch: true
47
47
  });
48
48
 
@@ -1,6 +1,5 @@
1
- import request, {existsInCache, getFirstArgPropertyName, getFromCache} from '../lib/request';
1
+ import request, {existsInCache, getFromCache} from '../lib/request';
2
2
 
3
- import Collection from '../lib/collection';
4
3
  import Model from '../lib/model';
5
4
  import ModelCache from '../lib/model-cache';
6
5
  import {waitsFor} from './test-utils';
@@ -29,7 +28,7 @@ describe('Request', () => {
29
28
  });
30
29
  }
31
30
 
32
- return Promise.resolve([new Model(), '', {response: {status: 200}}]);
31
+ return Promise.resolve([this, {status: 200}]);
33
32
  });
34
33
 
35
34
  jest.spyOn(ModelCache, 'put');
@@ -54,7 +53,7 @@ describe('Request', () => {
54
53
  describe('when using the default exported function', () => {
55
54
  it('returns a promise if the model does not exist', async() => {
56
55
  var model,
57
- promise = request('foo', Model, {component}).then(([_model]) => {
56
+ promise = request('foo', Model, {options: {one: 1}, component}).then(([_model]) => {
58
57
  model = _model;
59
58
  });
60
59
 
@@ -63,6 +62,8 @@ describe('Request', () => {
63
62
  expect(promise instanceof Promise).toBe(true);
64
63
  // in this instance we're resolving immediately, so model should be Model
65
64
  expect(model instanceof Model).toBe(true);
65
+ // this tests that it properly passes along the options object to the model constructor
66
+ expect(model.urlOptions).toEqual({one: 1});
66
67
  });
67
68
 
68
69
  describe('if the model does exist', () => {
@@ -303,15 +304,6 @@ describe('Request', () => {
303
304
  expect(getFromCache('bar')).not.toBeDefined();
304
305
  });
305
306
  });
306
-
307
- describe('getFirstArgPropertyName', () => {
308
- it('returns \'models\' for a collection, \'attributes\' for a model', () => {
309
- class _Collection extends Collection {}
310
- class _Model extends Model {}
311
- expect(getFirstArgPropertyName(_Collection)).toEqual('models');
312
- expect(getFirstArgPropertyName(_Model)).toEqual('attributes');
313
- });
314
- });
315
307
  });
316
308
 
317
309
  /**
package/test/sync.test.js CHANGED
@@ -35,60 +35,94 @@ describe('sync', () => {
35
35
 
36
36
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
37
37
  expect(window.fetch.mock.calls[0][1].method).toEqual('GET');
38
- expect(window.fetch.mock.calls[0][1].data).not.toBeDefined();
38
+ expect(window.fetch.mock.calls[0][1].params).not.toBeDefined();
39
39
  window.fetch.mockClear();
40
40
 
41
- await library.fetch({data: {one: 'two'}});
41
+ await library.fetch({params: {one: 'two'}});
42
42
  expect(window.fetch.mock.calls[0][0]).toEqual('/library?one=two');
43
43
  expect(window.fetch.mock.calls[0][1].method).toEqual('GET');
44
- expect(window.fetch.mock.calls[0][1].data).toEqual({one: 'two'});
44
+ expect(window.fetch.mock.calls[0][1].params).toEqual({one: 'two'});
45
45
  window.fetch.mockClear();
46
46
 
47
- await library.fetch({url: '/library?one=two', data: {two: 'three'}});
47
+ await library.fetch({url: '/library?one=two', params: {two: 'three'}});
48
48
  expect(window.fetch.mock.calls[0][0]).toEqual('/library?one=two&two=three');
49
49
  expect(window.fetch.mock.calls[0][1].method).toEqual('GET');
50
- expect(window.fetch.mock.calls[0][1].data).toEqual({two: 'three'});
50
+ expect(window.fetch.mock.calls[0][1].params).toEqual({two: 'three'});
51
51
  window.fetch.mockClear();
52
52
 
53
53
  // safe call with no options, even though this won't work
54
54
  expect(async() => sync(library)).not.toThrow();
55
55
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
56
56
  expect(window.fetch.mock.calls[0][1].method).not.toBeDefined();
57
- expect(window.fetch.mock.calls[0][1].data).not.toBeDefined();
57
+ expect(window.fetch.mock.calls[0][1].params).not.toBeDefined();
58
58
  });
59
59
 
60
- it('passing data', async() => {
60
+ it('passing params', async() => {
61
61
  // GET
62
- await library.fetch({data: {a: 'a', one: 1}});
62
+ await library.fetch({params: {a: 'a', one: 1}});
63
63
 
64
64
  expect(window.fetch.mock.calls[0][0]).toEqual('/library?a=a&one=1');
65
65
  window.fetch.mockClear();
66
66
 
67
67
  // with body content: already stringified
68
- await library.add(attrs).at(0).save(null, {data: 'somestring'});
68
+ await library.add(attrs).at(0).save(null, {params: 'somestring'});
69
69
 
70
70
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
71
71
  expect(window.fetch.mock.calls[0][1].body).toEqual('somestring');
72
72
  window.fetch.mockClear();
73
73
 
74
74
  // with body content: as JSON
75
- await library.at(0).save(null, {data: {a: 'a', one: 1}});
75
+ await library.at(0).save(null, {params: {a: 'a', one: 1}});
76
76
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
77
77
  expect(window.fetch.mock.calls[0][1].body).toEqual(JSON.stringify({a: 'a', one: 1}));
78
78
  window.fetch.mockClear();
79
79
 
80
80
  // with body content: not as json
81
- await library.at(0).save(null, {data: {a: 'a', one: 1}, contentType: 'resourcerer/json'});
81
+ await library.at(0).save(null, {params: {a: 'a', one: 1}, contentType: 'resourcerer/json'});
82
82
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
83
83
  expect(window.fetch.mock.calls[0][1].body).toEqual('a=a&one=1');
84
84
  });
85
85
 
86
+ it('passes urlOptions to the model to formulate the url path', async() => {
87
+ var librarySectionBook;
88
+
89
+ class LibrarySection extends Collection {
90
+ url({section}) {
91
+ return `/library/${section}`;
92
+ }
93
+ }
94
+
95
+ class LibrarySectionBook extends Model {
96
+ url({section, bookId}) {
97
+ return `/library/${section}/${bookId}`;
98
+ }
99
+ }
100
+
101
+ library = new LibrarySection([], {section: 'nature'});
102
+ await library.fetch({params: {a: 'a', one: 1}});
103
+
104
+ expect(window.fetch.mock.calls[0][0]).toEqual('/library/nature?a=a&one=1');
105
+ // safe
106
+ library = new LibrarySection();
107
+ await library.fetch({params: {a: 'a', one: 1}});
108
+ expect(window.fetch.mock.calls[1][0]).toEqual('/library/undefined?a=a&one=1');
109
+
110
+ librarySectionBook = new LibrarySectionBook({}, {section: 'nature', bookId: 'all-about-frogs'});
111
+ await librarySectionBook.fetch({params: {a: 'a', one: 1}});
112
+ expect(window.fetch.mock.calls[2][0]).toEqual('/library/nature/all-about-frogs?a=a&one=1');
113
+
114
+ // safe
115
+ librarySectionBook = new LibrarySectionBook();
116
+ await librarySectionBook.fetch({params: {a: 'a', one: 1}});
117
+ expect(window.fetch.mock.calls[3][0]).toEqual('/library/undefined/undefined?a=a&one=1');
118
+ });
119
+
86
120
  it('create', async() => {
87
121
  await library.create(attrs, {wait: false});
88
122
 
89
123
  expect(window.fetch.mock.calls[0][0]).toEqual('/library');
90
124
  expect(window.fetch.mock.calls[0][1].method).toEqual('POST');
91
- expect(window.fetch.mock.calls[0][1].data).toEqual({
125
+ expect(window.fetch.mock.calls[0][1].params).toEqual({
92
126
  title: 'The Tempest',
93
127
  author: 'Bill Shakespeare',
94
128
  length: 123
@@ -101,7 +135,7 @@ describe('sync', () => {
101
135
 
102
136
  expect(window.fetch.mock.calls[0][0]).toEqual('/library/1-the-tempest');
103
137
  expect(window.fetch.mock.calls[0][1].method).toEqual('PUT');
104
- expect(window.fetch.mock.calls[0][1].data).toEqual({
138
+ expect(window.fetch.mock.calls[0][1].params).toEqual({
105
139
  id: '1-the-tempest',
106
140
  title: 'The Tempest',
107
141
  author: 'William Shakespeare',
@@ -116,7 +150,7 @@ describe('sync', () => {
116
150
 
117
151
  expect(window.fetch.mock.calls[1][0]).toEqual('/library/2-the-tempest');
118
152
  expect(window.fetch.mock.calls[1][1].method).toEqual('GET');
119
- expect(window.fetch.mock.calls[1][1].data).not.toBeDefined();
153
+ expect(window.fetch.mock.calls[1][1].params).not.toBeDefined();
120
154
  });
121
155
 
122
156
  it('destroy', async() => {
@@ -126,7 +160,7 @@ describe('sync', () => {
126
160
 
127
161
  expect(window.fetch.mock.calls[1][0]).toEqual('/library/2-the-tempest');
128
162
  expect(window.fetch.mock.calls[1][1].method).toEqual('DELETE');
129
- expect(window.fetch.mock.calls[1][1].data).not.toBeDefined();
163
+ expect(window.fetch.mock.calls[1][1].params).not.toBeDefined();
130
164
  });
131
165
 
132
166
  it('rejects non-2xx', async() => {
@@ -190,6 +190,7 @@ describe('Utils', () => {
190
190
  describe('result', () => {
191
191
  it('returns the correct value if a function', () => {
192
192
  expect(result({foo: () => 'bar'}, 'foo')).toEqual('bar');
193
+ expect(result({foo: (x, y) => x + y + 5}, 'foo', 10, 5)).toEqual(20);
193
194
  });
194
195
 
195
196
  it('returns the correct value if not a function', () => {