resourcerer 1.0.0-beta-1 → 1.0.0-beta-5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,6 +17,7 @@ Additional features include:
17
17
  * refetching
18
18
  * updating a component when a resource updates
19
19
  * zero dependencies
20
+ * < 10kB!
20
21
  * ...and more
21
22
 
22
23
  Getting started is easy:
@@ -126,25 +127,27 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
126
127
  1. [Nomenclature](#nomenclature)
127
128
  1. [Tutorial](#tutorial)
128
129
  1. [Intro](#tutorial)
129
- 1. [Other Props Returned from the Hook/Passed from the HOC (Loading States)](other-props-returned-from-the-hookpassed-from-the-hoc-loading-states)
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)
130
131
  1. [Requesting Prop-driven Data](#requesting-prop-driven-data)
131
132
  1. [Changing Props](#changing-props)
132
- 1. [Serial Requests](#serial-requests)
133
- 1. [Other Common Resource Config Options](#other-common-resource-config-options)
134
- 1. [data](#data)
133
+ 1. [Common Resource Config Options](#common-resource-config-options)
134
+ 1. [params](#params)
135
135
  1. [options](#options)
136
- 1. [attributes](#attributes)
137
136
  1. [noncritical](#noncritical)
138
137
  1. [forceFetch](#forcefetch)
139
138
  1. [Custom Resource Names](#custom-resource-names)
140
139
  1. [prefetches](#prefetches)
140
+ 1. [data](#data)
141
+ 1. [dependsOn](#dependson)
142
+ 1. [provides](#provides)
141
143
  1. [Data mutations](#data-mutations)
142
- 1. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
143
- 1. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
144
- 1. [Declarative Cache Keys](#declarative-cache-keys)
145
- 1. [Prefetch on Hover](#prefetch-on-hover)
146
- 1. [Refetching](#refetching)
147
- 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)
148
151
  1. [Configuring resourcerer](#configuring-resourcerer)
149
152
  1. [FAQs](#faqs)
150
153
 
@@ -153,7 +156,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
153
156
 
154
157
  `$ npm i resourcerer`
155
158
 
156
- `resourcerer` requires on React >= 16 but has no external dependencies.
159
+ `resourcerer` requires on React >= 16.8 but has no external dependencies.
157
160
 
158
161
  Note that Resourcerer uses ES2015 in its source and does no transpiling&mdash;including import/export (Local babel configuration is for testing, only).
159
162
  This means that if you're not babelifying your `node_modules` folder, you'll need to make an exception for this package, ie:
@@ -173,7 +176,7 @@ module: {
173
176
 
174
177
  1. **Props**. Going forward in this tutorial, we'll try to describe behavior of both the `useResources` hook and the `withResources` HOC at once; we'll also rotate between the two in examples. Note that if we talking about a passed prop of, for example `isLoading`, that that corresponds to an `isLoading` property returned from the hook and a `this.props.isLoading` prop passed down from the HOC.
175
178
 
176
- 1. **ResourceKeys**. These are the keys added to the `ModelMap` in the introduction that link to your model constructors. They are passed to the executor functions and are used to tell the hook or HOC which resources to request.
179
+ 1. **ResourceKeys**. These are the keys added to the `ModelMap` (discussed above in the introduction) that link to your model constructors. They are passed to the executor functions and are used to tell the hook or HOC which resources to request.
177
180
 
178
181
  1. **Executor Function**. The executor function is a function that both the hook and HOC accept that declaratively describes which resources to request and with what config options. It accepts `ResourceKeys` and `props` as arguments and may look like, as we'll explore in an example later:
179
182
 
@@ -189,7 +192,7 @@ module: {
189
192
 
190
193
  return {
191
194
  [USER_TODOS]: {
192
- data: {
195
+ params: {
193
196
  limit: 20,
194
197
  end_time: now,
195
198
  start_time: now - props.timeRange,
@@ -209,8 +212,9 @@ module: {
209
212
  Okay, back to the initial example. Let's take a look at our `useResources` usage in the component:
210
213
 
211
214
  ```js
212
- // Note: in these docs, you will see a combination of `ResourceKeys` in the executor function as well as
213
- // its more common destructured version, ie `@withResources(({TODOS}, props) => ({[TODOS]: {}}))`
215
+ // Note: in these docs, you will see a combination of `ResourceKeys` in the executor
216
+ // function as well as its more common destructured version, ie:
217
+ // `@withResources(({TODOS}, props) => ({[TODOS]: {}}))`
214
218
  const getResources = (ResourceKeys, props) => ({[ResourceKeys.TODOS]: {}});
215
219
 
216
220
  export default function MyComponent(props) {
@@ -238,15 +242,15 @@ ModelMap.add({TODOS: TodosCollection});
238
242
 
239
243
  (We can also pass custom prefixes for our prop names in a component, but [we'll get to that later](#custom-resource-names).)
240
244
 
241
- Back to the executor function. In the example above, you see it returns an object of `{[ResourceKeys.TODOS]: {}}`. In general, the object it should return is of type `{string<ResourceKey>: object<Options>}`, where `Options` is a generic map of config options, and can contain as many keys as resources you would like the component to request. In our initial example, the options object was empty. Further down, we'll go over the plethora of options and how to use them. For now let's take a look at some of the resource-related props this simple configuration provides our component.
245
+ Back to the executor function. In the example above, you see it returns an object of `{[ResourceKeys.TODOS]: {}}`. In general, the object it should return is of type `{string<ResourceKey>: object<Options>}`, where `Options` is a generic map of config options. It can contain as many keys as resources you would like the component to request. In our initial example, the options object was empty. Further down, we'll go over the plethora of options and how to use them. For now let's take a look at some of the resource-related props this simple configuration provides our component.
242
246
 
243
247
 
244
248
  ## Other Props Returned from the Hook/Passed from the HOC (Loading States)
245
249
 
246
- Of course, in our initial example, the todos collection won’t get passed down immediately since, after all, the resource has to be fetched from the API. Some of the most **significant** and most common React UI states we utilize are whether a component’s critical resources have loaded entirely, whether any are still loading, or whether any have errored out. This is how we can appropriately cover our bases&mdash;i.e., we can ensure the component shows a loader while the resource is still in route, or if something goes wrong, we can ensure the component will still fail gracefully and not break the layout. To address these concerns, the `useResources` hook/`withResources` HOC gives you several loading state helper props. From our last example:
250
+ Of course, in our initial example, the `todosCollection` won’t be populated with data immediately since, after all, the resource has to be fetched from the API. Some of the most **significant** and most common React UI states we utilize are whether a component’s critical resources have loaded entirely, whether any are still loading, or whether any have errored out. This is how we can appropriately cover our bases&mdash;i.e., we can ensure the component shows a loader while the resource is still in route, or if something goes wrong, we can ensure the component will still fail gracefully and not break the layout. To address these concerns, the `useResources` hook/`withResources` HOC gives you several loading state helper props. From our last example:
247
251
 
248
252
 
249
- - `todosLoadingState` (can be equal to any of the [LoadingStates constants](https://github.com/noahgrant/resourcerer/blob/master/lib/constants.js), and there will be one for each resource)
253
+ - `todosLoadingState` (can be equal to any of the [LoadingStates constants](https://github.com/noahgrant/resourcerer/blob/master/lib/constants.js). There will be one for each resource, and the property names will be equal to `${resourceKey}LoadingState`)
250
254
  - `hasLoaded` {boolean} - all critical resources have successfully completed and are ready to be used by the component
251
255
  - `isLoading` {boolean} - any of the critical resources are still in the process of being fetched
252
256
  - `hasErrored` {boolean} - any of the critical resource requests did not complete successfully
@@ -254,7 +258,7 @@ Of course, in our initial example, the todos collection won’t get passed down
254
258
  `isLoading` , `hasLoaded` , and `hasErrored` are not based on individual loading states, but are rather a collective loading state for the aforementioned-critical component resources. In the previous example, the todos resource is the only critical resource, so `isLoading` / `hasLoaded` / `hasErrored` are solely based on `todosLoadingState`. But we can also add a non-critical `users` resource, responsible, say, for only display users' names alongside their TODOs&mdash;a small piece of the overall component and not worth delaying render over. Here’s how we do that:
255
259
 
256
260
  ```js
257
- const getResources = ({TODOS, USER}, props) => ({
261
+ const getResources = ({TODOS, USERS}, props) => ({
258
262
  [TODOS]: {},
259
263
  [USERS]: {noncritical: true}
260
264
  });
@@ -306,7 +310,8 @@ function MyClassWithTodosAndAUsers(props) {
306
310
 
307
311
  {hasLoaded ? (
308
312
  // at this point we are guaranteed all critical resources have returned.
309
- // before that, todosCollection is a Collection instance, just empty
313
+ // before that, todosCollection is still a Collection instance that can be
314
+ // mapped over--it's just empty
310
315
  <ul>
311
316
  {todosCollection.map((todoModel) => (
312
317
  <li key={todoModel.id}>
@@ -335,7 +340,7 @@ And here's what it looks like when the stats endpoint returns:
335
340
 
336
341
  ![Noncritical Resource Returned](https://user-images.githubusercontent.com/1355779/57596646-9a425900-7500-11e9-8121-5ced72c0fcba.png)
337
342
 
338
- There’s one other loading prop offered from the hook/HOC: `hasInitiallyLoaded`. This can be useful for showing a different UI for components that have already fetched the resource. An example might be a component with filters: as the initial resource is fetched, we may want to show a generic loader, but upon changing a filter (and re-fetching the resource), we may want to show a loader with an overlay over the previous version of the component. See the [Advanced Topics docs](/docs/advanced_topics.md#loading-overlays) for more.
343
+ There’s one other loading prop offered from the hook/HOC: `hasInitiallyLoaded`. This can be useful for showing a different UI for components that have already fetched the resource. An example might be a component with filters: when a filter is changed after the initial resource is loaded (thus re-fetching the resource), we may want to show a loader with an overlay over the previous version of the component. See the [Advanced Topics docs](/docs/advanced_topics.md#loading-overlays) for more.
339
344
 
340
345
 
341
346
  ## Requesting Prop-driven Data
@@ -361,25 +366,23 @@ And here's what our model might look like:
361
366
  import {Model} from 'resourcerer';
362
367
 
363
368
  export default class UserModel extends Model {
364
- constructor(attributes, options={}) {
365
- this.userId = options.userId;
366
- }
367
-
368
- url() {
369
- 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}`;
370
373
  }
371
374
 
372
375
  static cacheFields = ['userId']
373
376
  }
374
377
  ```
375
378
 
376
- The `cacheFields` static property is important here, as we'll see in a second; it is a list of model 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:
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:
377
380
 
378
- 1. the `options` object it is initialized with
379
- 1. the `attributes` object it is initialized with
380
- 1. the `data` it gets passed in a fetch
381
+ 1. the `options` object
382
+ 1. the `data` object
383
+ 1. the `params` object
381
384
 
382
- All three of these come from what's returned from our executor function; it might look like this:
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:
383
386
 
384
387
  ```jsx
385
388
  const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}})
@@ -412,71 +415,12 @@ In general, there are two ways to change `props.id` as in the previous example:
412
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.
413
416
 
414
417
 
415
- ## Serial Requests
416
-
417
- 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 option and the `provides` resource 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.
418
-
419
- ```js
420
- @withResources(({QUEUE_ITEM, USER}, props) => ({
421
- [USER]: {
422
- options: {userId: props.userId},
423
- dependsOn: ['userId']
424
- },
425
- [QUEUE_ITEM]: {
426
- attributes: {id: props.itemId}
427
- provides: {userId: getUserIdFromItem}
428
- }
429
- }))
430
- export default class QueueItemPage extends React.Component {}
431
-
432
- function getUserIdFromItem(queueItemModel) {
433
- return queueItemModel.get('userId');
434
- }
435
- ```
436
-
437
- 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.
438
-
439
- 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 for the HOC wrapper’s state wrapper 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!
440
-
441
- 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).
442
-
443
- 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:
444
-
445
- ```js
446
- const getResources = ({QUEUE_ITEM, USER}, props) => ({
447
- [USER]: {
448
- options: {state: props.activeState, userId: props.userId},
449
- // userModel depends on multiple props from queueItemModel
450
- dependsOn: ['activeState', 'userId']
451
- },
452
- [QUEUE_ITEM]: {
453
- attributes: {id: props.itemId}
454
- // use an underscore here to tell resourcerer to spread the resulting object
455
- provides: {_: getUserDataFromItem}
456
- }
457
- });
458
-
459
- export default function QueueItemPage(props) {
460
- // activeState and userId are internal state within `useResources` and returned
461
- var {
462
- activeState,
463
- userId,
464
- userModel,
465
- queueItemModel
466
- } = useResources(getResources, props);
467
- }
468
-
469
- function getUserDataFromItem(queueItemModel) {
470
- // transform function now returns an object of prop names/values instead of a simple prop value
471
- return {userId: queueItemModel.get('userId'), activeState: queueItemModel.get('state')};
472
- }
473
- ```
474
418
 
475
- ## Other Common Resource Config Options
419
+ ## Common Resource Config Options
476
420
 
477
- ### data
421
+ ### params
478
422
 
479
- The `data` option is passed directly to the [sync](/docs/model.md#sync) module 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:
480
424
 
481
425
  ```js
482
426
  @withResources((ResourceKeys, props) => {
@@ -484,7 +428,7 @@ The `data` option is passed directly to the [sync](/docs/model.md#sync) module a
484
428
 
485
429
  return {
486
430
  [ResourceKeys.USER_TODOS]: {
487
- data: {
431
+ params: {
488
432
  limit: 20,
489
433
  end_time: now,
490
434
  start_time: now - props.timeRange,
@@ -496,13 +440,14 @@ The `data` option is passed directly to the [sync](/docs/model.md#sync) module a
496
440
  class UserTodos extends React.Component {}
497
441
  ```
498
442
 
499
- 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):
500
444
 
501
445
  `https://example.com/users/noahgrant/todos?limit=20&end_time=1494611831024&start_time=1492019831024&sort_field=importance`
502
446
 
503
- ### options
504
447
 
505
- [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:
506
451
 
507
452
  ```js
508
453
  const getResources = (ResourceKeys, props) => {
@@ -510,7 +455,7 @@ const getResources = (ResourceKeys, props) => {
510
455
 
511
456
  return {
512
457
  [ResourceKeys.USER_TODOS]: {
513
- data: {
458
+ params: {
514
459
  limit: 20,
515
460
  end_time: now,
516
461
  start_time: now - props.timeRange,
@@ -522,11 +467,19 @@ const getResources = (ResourceKeys, props) => {
522
467
  };
523
468
  ```
524
469
 
525
- 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.
526
-
527
- ### attributes
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:
528
471
 
529
- 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) or [collection's](/docs/collection.md#constructor) `constructor` method along with the [`options`](#options) property, and is typically 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).
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
+ ```
530
483
 
531
484
 
532
485
  ### noncritical
@@ -580,7 +533,7 @@ const getResources = (ResourceKeys, props) => {
580
533
 
581
534
  return {
582
535
  [ResourceKeys.USER_TODOS]: {
583
- data: {
536
+ params: {
584
537
  from: props.page * REQUESTS_PER_PAGE,
585
538
  limit: REQUESTS_PER_PAGE,
586
539
  end_time: now,
@@ -605,6 +558,33 @@ When the user clicks on a 'next' arrow that updates page state, the collection w
605
558
 
606
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.
607
560
 
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.
579
+
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).
587
+
608
588
  # Data Mutations
609
589
 
610
590
  So far we've only discussed fetching data. But `resourcerer` also makes it very easy to make write requests via the [Model](/docs/model.md) and [Collection](/docs/collection.md) instances that are returned. These classes are enriched data structures that hold our API server data as well as several utilities that help manage the server data in our application. There are three main write operations via these classes:
@@ -676,7 +656,67 @@ Each one of these methods exhibit the following behaviors:
676
656
  **Note:**
677
657
  1. All calls resolve an array, which is a tuple of [model, response]. All reject with just the response.
678
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
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.
679
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
+ ```
680
720
 
681
721
  # Differences between useResources and withResources
682
722
 
@@ -684,11 +724,11 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
684
724
 
685
725
  1. The `withResources` HOC conveniently contains an [ErrorBoundary](https://reactjs.org/docs/error-boundaries.html) with every instance, but such functionality [does not yet exist in hooks](https://reactjs.org/docs/hooks-faq.html#do-hooks-cover-all-use-cases-for-classes). This is a definite advantage for the HOC right now, since, if we're already setting `hasErrored` clauses in our components to prepare for request errors, we can naturally gracefully degrade when an unexpected exception occurs. You'll need to manage this yourself with hooks until the equivalent functionality is released.
686
726
 
687
- 1. With the executor function now inlined in your component, be extra careful to avoid this anti-pattern:
727
+ 1. The executor function for a hook can be inlined in your component, which puts component props in its closure scope. So be extra careful to avoid this anti-pattern:
688
728
 
689
729
  ```js
690
730
  function MyComponent({start_time, ...props}) {
691
- var {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {data: {start_time}}}), props);
731
+ var {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {params: {start_time}}}), props);
692
732
 
693
733
  // ...
694
734
  ```
@@ -697,15 +737,15 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
697
737
 
698
738
  ```js
699
739
  function MyComponent(props) {
700
- var {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}}), props);
740
+ var {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
701
741
 
702
742
  // ...
703
743
  ```
704
744
 
705
- or define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
745
+ or, even clearer, define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
706
746
 
707
747
  ```js
708
- const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}});
748
+ const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}});
709
749
 
710
750
  function MyComponent(props) {
711
751
  var {todosCollection} = useResources(getResources, props);
@@ -725,7 +765,7 @@ Again, it’s unlikely that you’ll use `ModelCache` directly while using `reso
725
765
 
726
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:
727
767
 
728
- 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.
729
769
 
730
770
  2. A function, whose return value is an object of keys and values that should both contribute to the cache key.
731
771
 
@@ -737,7 +777,7 @@ const getResources = (ResourceKeys, props) => {
737
777
 
738
778
  return {
739
779
  [ResourceKeys.USER_TODOS]: {
740
- data: {
780
+ params: {
741
781
  limit: props.limit,
742
782
  end_time: now,
743
783
  start_time: now - props.timeRange,
@@ -753,12 +793,8 @@ And our corresponding model definition might look like this:
753
793
 
754
794
  ```js
755
795
  export class UserTodosCollection extends Collection {
756
- constructor(models, options={}) {
757
- this.userId = options.userId;
758
- }
759
-
760
- url() {
761
- return `/users/${this.userId}/todos`;
796
+ url({userId}) {
797
+ return `/users/${userId}/todos`;
762
798
  }
763
799
  // ...
764
800
 
@@ -771,15 +807,15 @@ export class UserTodosCollection extends Collection {
771
807
  };
772
808
  ```
773
809
 
774
- 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.
775
811
 
776
- 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.
777
813
 
778
814
  The generated cache key would be something like `userTodos_limit=50_$range=86400000_sort_field=importance_userId=noah`. Again, note that:
779
815
 
780
816
  - the `userId` value is taken from the `options` hash
781
- - the `limit` and `sort_field` values are taken from the `data` hash
782
- - 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.
783
819
 
784
820
 
785
821
  ## Prefetch on Hover
@@ -790,12 +826,12 @@ You can use `resourcerer`'s executor function to optimistically prefetch resourc
790
826
  import {prefetch} from 'resourcerer';
791
827
 
792
828
  // here's our executor function just as we pass to useResources or withResources
793
- const getTodos = (props, ResourceKeys) => {
829
+ const getTodos = (ResourceKeys, props) => {
794
830
  const now = Date.now();
795
831
 
796
832
  return {
797
833
  [ResourceKeys.USER_TODOS]: {
798
- data: {
834
+ params: {
799
835
  limit: props.limit,
800
836
  end_time: now,
801
837
  start_time: now - props.timeRange,
@@ -825,7 +861,7 @@ It takes a function that is passed `ResourceKeys` and should return a list of `R
825
861
 
826
862
  ```js
827
863
  function MyComponent(props) {
828
- 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);
829
865
 
830
866
  // ...
831
867
 
@@ -848,7 +884,7 @@ class MyMeasuredModel extends Model {
848
884
  static measure = true
849
885
 
850
886
  // or a function that returns a boolean, which will track instance requests based on a condition
851
- static measure = ({attributes={}}) => attributes.id === 'noahgrant'
887
+ static measure = ({data={}}) => data.id === 'noahgrant'
852
888
  }
853
889
  ```
854
890
 
@@ -907,22 +943,22 @@ ResourcesConfig.set(configObj);
907
943
  import {stringify} from 'qs';
908
944
 
909
945
  ResourcesConfig.set({
910
- stringify(data, options) {
911
- // 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
912
948
  // options is the request options object
913
- return stringify(data);
949
+ return stringify(params);
914
950
  }
915
951
  });
916
952
  ```
917
953
 
918
954
  * `queryParamsPropName` (string): the name of the prop representing url query parameters that `withResources` will look for and flatten for its children. If your application already flattens query parameters, you can ignore this property. Otherwise, when a url search string of, for example, `?end_time=1558100000000&start_time=1555508000000` is turned into an object prop of `{end_time: 1558100000000, start_time: 1555508000000}`, `withResources`-wrapped components will see `props.end_time` and `props.start_time`, and `useResources` will return `end_time` and `start_time` for ease of use in your executor function. **Default:** `'urlParams'`.
919
955
 
920
- * `track` (function): method invoked when [`measure: true`](#measure) is passed in a resource's config. Use this hook to send the measured data to your application analytics tracker. **Default:** noop. The method is invoked with two arguments:
956
+ * `track` (function): method invoked when [a `measure` property is added to a Model or Collection](#tracking-request-times). Use this hook to send the measured data to your application analytics tracker. **Default:** noop. The method is invoked with two arguments:
921
957
 
922
958
  * the event string, `'API Fetch'`
923
959
  * event data object with the following properties:
924
960
  * Resource (string): the name of the resource (taken from the entry in `ResourceKeys`)
925
- * data (object): data object supplied via the resource's config
961
+ * params (object): params object supplied via the resource's config
926
962
  * options (object): options object supplied via the resource's config
927
963
  * duration (number): time in milliseconds between request and response
928
964
 
@@ -1027,7 +1063,7 @@ ResourcesConfig.set(configObj);
1027
1063
 
1028
1064
  return {
1029
1065
  [ResourceKeys.USER_TODOS]: {
1030
- data: {
1066
+ params: {
1031
1067
  limit: 20,
1032
1068
  end_time: now,
1033
1069
  start_time: now - props.timeRange,
@@ -1043,7 +1079,7 @@ ResourcesConfig.set(configObj);
1043
1079
 
1044
1080
  * Can `resourcerer` do anything other than `GET` requests?
1045
1081
 
1046
- `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.
1047
1083
 
1048
1084
  For write operations, use Models' [`save`](/docs/model.md#save) and [`destroy`](/docs/model.md#destroy) methods directly:
1049
1085
 
package/index.js CHANGED
@@ -12,9 +12,3 @@ export {
12
12
  } from './lib/utils.js';
13
13
  export {ModelMap, ResourceKeys, ResourcesConfig} from './lib/config.js';
14
14
  export {useResources, withResources} from './lib/resourcerer.js';
15
- export {
16
- findDataCarrier,
17
- findDataChild,
18
- getRenderedResourceComponents,
19
- waitsFor
20
- } from './test/test-utils.js';