resourcerer 1.0.0-beta-3 → 1.0.1
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 +170 -139
- package/lib/collection.js +37 -13
- package/lib/config.js +3 -3
- package/lib/model.js +11 -2
- package/lib/request.js +18 -23
- package/lib/resourcerer.js +30 -36
- package/lib/sync.js +17 -16
- package/lib/utils.js +2 -2
- package/package.json +1 -1
- package/test/collection.test.js +32 -7
- package/test/model-mocks.js +7 -26
- package/test/model.test.js +22 -0
- package/test/prefetch.test.js +3 -3
- package/test/request.test.js +56 -21
- package/test/sync.test.js +49 -15
- package/test/utils.test.js +1 -0
package/README.md
CHANGED
|
@@ -12,13 +12,13 @@
|
|
|
12
12
|
|
|
13
13
|
Additional features include:
|
|
14
14
|
|
|
15
|
+
* fully declarative (no more writing any imperative Fetch API calls)
|
|
15
16
|
* first-class loading and error state support
|
|
16
17
|
* smart client-side caching
|
|
17
18
|
* refetching
|
|
18
19
|
* updating a component when a resource updates
|
|
19
20
|
* zero dependencies
|
|
20
21
|
* < 10kB!
|
|
21
|
-
* ...and more
|
|
22
22
|
|
|
23
23
|
Getting started is easy:
|
|
24
24
|
|
|
@@ -56,13 +56,12 @@ import 'js/core/resourcerer-config';
|
|
|
56
56
|
1. ### useResources
|
|
57
57
|
|
|
58
58
|
```jsx
|
|
59
|
-
import React from 'react';
|
|
60
59
|
import {useResources} from 'resourcerer';
|
|
61
60
|
|
|
62
61
|
const getResources = ({TODOS}, props) => ({[TODOS]: {}});
|
|
63
62
|
|
|
64
63
|
function MyComponent(props) {
|
|
65
|
-
|
|
64
|
+
const {
|
|
66
65
|
isLoading,
|
|
67
66
|
hasErrored,
|
|
68
67
|
hasLoaded,
|
|
@@ -127,25 +126,27 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
|
|
|
127
126
|
1. [Nomenclature](#nomenclature)
|
|
128
127
|
1. [Tutorial](#tutorial)
|
|
129
128
|
1. [Intro](#tutorial)
|
|
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)
|
|
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)
|
|
131
130
|
1. [Requesting Prop-driven Data](#requesting-prop-driven-data)
|
|
132
131
|
1. [Changing Props](#changing-props)
|
|
133
|
-
1. [
|
|
134
|
-
|
|
135
|
-
1. [data](#data)
|
|
132
|
+
1. [Common Resource Config Options](#common-resource-config-options)
|
|
133
|
+
1. [params](#params)
|
|
136
134
|
1. [options](#options)
|
|
137
135
|
1. [noncritical](#noncritical)
|
|
138
|
-
1. [
|
|
136
|
+
1. [force](#force)
|
|
139
137
|
1. [Custom Resource Names](#custom-resource-names)
|
|
140
138
|
1. [prefetches](#prefetches)
|
|
141
|
-
1. [
|
|
139
|
+
1. [data](#data)
|
|
140
|
+
1. [dependsOn](#dependson)
|
|
141
|
+
1. [provides](#provides)
|
|
142
142
|
1. [Data mutations](#data-mutations)
|
|
143
|
-
1. [
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
143
|
+
1. [Serial Requests](#serial-requests)
|
|
144
|
+
3. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
|
|
145
|
+
4. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
|
|
146
|
+
5. [Declarative Cache Keys](#declarative-cache-keys)
|
|
147
|
+
6. [Prefetch on Hover](#prefetch-on-hover)
|
|
148
|
+
7. [Refetching](#refetching)
|
|
149
|
+
8. [Tracking Request Times](#tracking-request-times)
|
|
149
150
|
1. [Configuring resourcerer](#configuring-resourcerer)
|
|
150
151
|
1. [FAQs](#faqs)
|
|
151
152
|
|
|
@@ -176,7 +177,7 @@ module: {
|
|
|
176
177
|
|
|
177
178
|
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.
|
|
178
179
|
|
|
179
|
-
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:
|
|
180
|
+
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. In these docs you'll often see it assigned to a variable called `getResources`. It accepts `ResourceKeys` and `props` as arguments and may look like, as we'll explore in an example later:
|
|
180
181
|
|
|
181
182
|
```js
|
|
182
183
|
const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}});
|
|
@@ -190,7 +191,7 @@ module: {
|
|
|
190
191
|
|
|
191
192
|
return {
|
|
192
193
|
[USER_TODOS]: {
|
|
193
|
-
|
|
194
|
+
params: {
|
|
194
195
|
limit: 20,
|
|
195
196
|
end_time: now,
|
|
196
197
|
start_time: now - props.timeRange,
|
|
@@ -201,7 +202,7 @@ module: {
|
|
|
201
202
|
};
|
|
202
203
|
```
|
|
203
204
|
|
|
204
|
-
It returns an object whose keys represent the resources to fetch and whose values are
|
|
205
|
+
It returns an object whose keys represent the resources to fetch and whose values are **Resource Configuration Objects** that we'll discuss later (and is highlighted below).
|
|
205
206
|
|
|
206
207
|
1. **Resource Configuration Object (resource config)**. In the object returned by our executor function, each entry has a key equal to one of the `ResourceKeys` and whose value we will refer to in this document as a Resource Configuration Object. It holds the declarative instructions that `useResources` and `withResources` will use to request the resource.
|
|
207
208
|
|
|
@@ -216,7 +217,7 @@ Okay, back to the initial example. Let's take a look at our `useResources` usage
|
|
|
216
217
|
const getResources = (ResourceKeys, props) => ({[ResourceKeys.TODOS]: {}});
|
|
217
218
|
|
|
218
219
|
export default function MyComponent(props) {
|
|
219
|
-
|
|
220
|
+
const resources = useResources(getResources, props);
|
|
220
221
|
|
|
221
222
|
// ...
|
|
222
223
|
}
|
|
@@ -262,7 +263,7 @@ const getResources = ({TODOS, USERS}, props) => ({
|
|
|
262
263
|
});
|
|
263
264
|
|
|
264
265
|
function MyClassWithTodosAndAUsers(props) {
|
|
265
|
-
|
|
266
|
+
const resources = useResources(getResources, props);
|
|
266
267
|
}
|
|
267
268
|
```
|
|
268
269
|
|
|
@@ -282,7 +283,7 @@ Here’s how might use that to our advantage in `MyClassWithTodosAndAUsers` :
|
|
|
282
283
|
import {haveAllLoaded} from 'resourcerer';
|
|
283
284
|
|
|
284
285
|
function MyClassWithTodosAndAUsers(props) {
|
|
285
|
-
|
|
286
|
+
const {
|
|
286
287
|
isLoading,
|
|
287
288
|
hasErrored,
|
|
288
289
|
hasLoaded,
|
|
@@ -364,12 +365,10 @@ And here's what our model might look like:
|
|
|
364
365
|
import {Model} from 'resourcerer';
|
|
365
366
|
|
|
366
367
|
export default class UserModel extends Model {
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
url() {
|
|
372
|
-
return `/users/${this.userId}`;
|
|
368
|
+
url({userId}) {
|
|
369
|
+
// `userId` is passed in here because we have
|
|
370
|
+
// `options: {userId: props.userId}` in the resource config object
|
|
371
|
+
return `/users/${userId}`;
|
|
373
372
|
}
|
|
374
373
|
|
|
375
374
|
static cacheFields = ['userId']
|
|
@@ -378,9 +377,9 @@ export default class UserModel extends Model {
|
|
|
378
377
|
|
|
379
378
|
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
379
|
|
|
381
|
-
1. the `options` object
|
|
382
|
-
1. the `
|
|
383
|
-
1. the `
|
|
380
|
+
1. the `options` object
|
|
381
|
+
1. the `data` object
|
|
382
|
+
1. the `params` object
|
|
384
383
|
|
|
385
384
|
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
385
|
|
|
@@ -389,7 +388,7 @@ const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}}
|
|
|
389
388
|
|
|
390
389
|
// hook
|
|
391
390
|
function MyComponent(props) {
|
|
392
|
-
|
|
391
|
+
const resources = useResources(getResources, props);
|
|
393
392
|
|
|
394
393
|
// ...
|
|
395
394
|
}
|
|
@@ -415,71 +414,12 @@ In general, there are two ways to change `props.id` as in the previous example:
|
|
|
415
414
|
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
415
|
|
|
417
416
|
|
|
418
|
-
## Serial Requests
|
|
419
417
|
|
|
420
|
-
|
|
418
|
+
## Common Resource Config Options
|
|
421
419
|
|
|
422
|
-
|
|
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—it takes its model as an argument and returns the value for the prop it provides.
|
|
420
|
+
### params
|
|
441
421
|
|
|
442
|
-
|
|
443
|
-
|
|
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:
|
|
422
|
+
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
423
|
|
|
484
424
|
```js
|
|
485
425
|
@withResources((ResourceKeys, props) => {
|
|
@@ -487,7 +427,7 @@ The `data` option is passed directly to the [sync method](/docs/model.md#sync) a
|
|
|
487
427
|
|
|
488
428
|
return {
|
|
489
429
|
[ResourceKeys.USER_TODOS]: {
|
|
490
|
-
|
|
430
|
+
params: {
|
|
491
431
|
limit: 20,
|
|
492
432
|
end_time: now,
|
|
493
433
|
start_time: now - props.timeRange,
|
|
@@ -499,13 +439,14 @@ The `data` option is passed directly to the [sync method](/docs/model.md#sync) a
|
|
|
499
439
|
class UserTodos extends React.Component {}
|
|
500
440
|
```
|
|
501
441
|
|
|
502
|
-
Now, as the prop fields change, the
|
|
442
|
+
Now, as the prop fields change, the params sent with the request changes as well (provided we set our `cacheFields` property accordingly):
|
|
503
443
|
|
|
504
444
|
`https://example.com/users/noahgrant/todos?limit=20&end_time=1494611831024&start_time=1492019831024&sort_field=importance`
|
|
505
445
|
|
|
506
|
-
### options
|
|
507
446
|
|
|
508
|
-
|
|
447
|
+
### options
|
|
448
|
+
|
|
449
|
+
[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
450
|
|
|
510
451
|
```js
|
|
511
452
|
const getResources = (ResourceKeys, props) => {
|
|
@@ -513,7 +454,7 @@ const getResources = (ResourceKeys, props) => {
|
|
|
513
454
|
|
|
514
455
|
return {
|
|
515
456
|
[ResourceKeys.USER_TODOS]: {
|
|
516
|
-
|
|
457
|
+
params: {
|
|
517
458
|
limit: 20,
|
|
518
459
|
end_time: now,
|
|
519
460
|
start_time: now - props.timeRange,
|
|
@@ -525,7 +466,19 @@ const getResources = (ResourceKeys, props) => {
|
|
|
525
466
|
};
|
|
526
467
|
```
|
|
527
468
|
|
|
528
|
-
Here,
|
|
469
|
+
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:
|
|
470
|
+
|
|
471
|
+
```js
|
|
472
|
+
// js/models/user_todos_collection.js
|
|
473
|
+
export class UserTodosCollection extends Collection {
|
|
474
|
+
url({userId}) {
|
|
475
|
+
// userId gets passed in for us to help construct our url
|
|
476
|
+
return `/users/${userId}/todos`;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
static cacheFields = ['userId']
|
|
480
|
+
};
|
|
481
|
+
```
|
|
529
482
|
|
|
530
483
|
|
|
531
484
|
### noncritical
|
|
@@ -538,12 +491,12 @@ As alluded to in the [Other Props](#other-props-returned-from-the-hookpassed-fro
|
|
|
538
491
|
|
|
539
492
|
|
|
540
493
|
|
|
541
|
-
###
|
|
494
|
+
### force
|
|
542
495
|
|
|
543
|
-
Sometimes you want the latest of a resource, bypassing whatever model has already been cached in your application. To accomplish this, simply pass a `
|
|
496
|
+
Sometimes you want the latest of a resource, bypassing whatever model has already been cached in your application. To accomplish this, simply pass a `force: true` in a resource's config. The force-fetched response will replace any prior model in the cache, but may itself get replaced by a subsequent `force: true` request for the resource.
|
|
544
497
|
|
|
545
498
|
```js
|
|
546
|
-
@withResources((ResourceKeys, props) => ({[ResourceKeys.LATEST_STATS]: {
|
|
499
|
+
@withResources((ResourceKeys, props) => ({[ResourceKeys.LATEST_STATS]: {force: true}}))
|
|
547
500
|
class MyComponentWithLatestStats extends React.Component {}
|
|
548
501
|
```
|
|
549
502
|
|
|
@@ -555,7 +508,7 @@ Passing a `modelKey: <ResourceKeys>` option allows you to pass a custom name as
|
|
|
555
508
|
const getResources = (ResourceKeys, props) => ({myRadTodos: {modelKey: ResourceKeys.TODOS});
|
|
556
509
|
|
|
557
510
|
export default function MyComponentWithTodos {
|
|
558
|
-
|
|
511
|
+
const {
|
|
559
512
|
myRadTodosCollection,
|
|
560
513
|
myRadTodosLoadingState,
|
|
561
514
|
myRadTodosStatus,
|
|
@@ -579,7 +532,7 @@ const getResources = (ResourceKeys, props) => {
|
|
|
579
532
|
|
|
580
533
|
return {
|
|
581
534
|
[ResourceKeys.USER_TODOS]: {
|
|
582
|
-
|
|
535
|
+
params: {
|
|
583
536
|
from: props.page * REQUESTS_PER_PAGE,
|
|
584
537
|
limit: REQUESTS_PER_PAGE,
|
|
585
538
|
end_time: now,
|
|
@@ -604,9 +557,32 @@ When the user clicks on a 'next' arrow that updates page state, the collection w
|
|
|
604
557
|
|
|
605
558
|
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
559
|
|
|
607
|
-
###
|
|
560
|
+
### data
|
|
561
|
+
|
|
562
|
+
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:
|
|
563
|
+
|
|
564
|
+
```js
|
|
565
|
+
getResources = ({CUSTOMER}) => ({[CUSTOMER]: {data: {id: props.customerId}}});
|
|
566
|
+
|
|
567
|
+
function MyCustomerComponent(props) {
|
|
568
|
+
const {customerModel} = useResources(getResources, props);
|
|
569
|
+
|
|
570
|
+
// now you can reference the id directly on the model
|
|
571
|
+
console.log(customerModel.get('id')); // or the id shorthand, customerModel.id
|
|
572
|
+
}
|
|
573
|
+
```
|
|
574
|
+
|
|
575
|
+
You can also use `data` to take advantage of [re-caching](/docs/advanced_topics.md#recaching-newly-saved-models).
|
|
608
576
|
|
|
609
|
-
|
|
577
|
+
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.
|
|
578
|
+
|
|
579
|
+
### dependsOn
|
|
580
|
+
|
|
581
|
+
See the section on [serial requests](#serial-requests).
|
|
582
|
+
|
|
583
|
+
### provides
|
|
584
|
+
|
|
585
|
+
See the section on [serial requests](#serial-requests).
|
|
610
586
|
|
|
611
587
|
# Data Mutations
|
|
612
588
|
|
|
@@ -618,10 +594,10 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
|
|
|
618
594
|
|
|
619
595
|
```js
|
|
620
596
|
function MyComponent(props) {
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
597
|
+
const {myModel} = useResources(getResources, props),
|
|
598
|
+
onSave = () => myModel.save({foo: 'bar'})
|
|
599
|
+
.then([model]) => // ...)
|
|
600
|
+
.catch(() => alert('request failed'));
|
|
625
601
|
|
|
626
602
|
return <button onClick={onSave}>Persist model</button>;
|
|
627
603
|
}
|
|
@@ -641,8 +617,8 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
|
|
|
641
617
|
|
|
642
618
|
```js
|
|
643
619
|
function TodoDetails(props) {
|
|
644
|
-
|
|
645
|
-
|
|
620
|
+
const {hasLoaded, todosCollection} = useResources(getResources, props),
|
|
621
|
+
todoModel = todosCollection.get(props.id),
|
|
646
622
|
|
|
647
623
|
onSaveTodo = {
|
|
648
624
|
// set some loading state...
|
|
@@ -679,7 +655,66 @@ Each one of these methods exhibit the following behaviors:
|
|
|
679
655
|
**Note:**
|
|
680
656
|
1. All calls resolve an array, which is a tuple of [model, response]. All reject with just the response.
|
|
681
657
|
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.
|
|
658
|
+
|
|
659
|
+
## Serial Requests
|
|
682
660
|
|
|
661
|
+
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.
|
|
662
|
+
|
|
663
|
+
```js
|
|
664
|
+
@withResources(({QUEUE_ITEM, USER}, props) => ({
|
|
665
|
+
[USER]: {
|
|
666
|
+
options: {userId: props.userId},
|
|
667
|
+
dependsOn: ['userId']
|
|
668
|
+
},
|
|
669
|
+
[QUEUE_ITEM]: {
|
|
670
|
+
data: {id: props.itemId}
|
|
671
|
+
provides: {userId: getUserIdFromItem}
|
|
672
|
+
}
|
|
673
|
+
}))
|
|
674
|
+
export default class QueueItemPage extends React.Component {}
|
|
675
|
+
|
|
676
|
+
function getUserIdFromItem(queueItemModel) {
|
|
677
|
+
return queueItemModel.get('userId');
|
|
678
|
+
}
|
|
679
|
+
```
|
|
680
|
+
|
|
681
|
+
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—it takes its model as an argument and returns the value for the prop it provides.
|
|
682
|
+
|
|
683
|
+
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!
|
|
684
|
+
|
|
685
|
+
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).
|
|
686
|
+
|
|
687
|
+
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:
|
|
688
|
+
|
|
689
|
+
```js
|
|
690
|
+
const getResources = ({QUEUE_ITEM, USER}, props) => ({
|
|
691
|
+
[USER]: {
|
|
692
|
+
options: {state: props.activeState, userId: props.userId},
|
|
693
|
+
// userModel depends on multiple props from queueItemModel
|
|
694
|
+
dependsOn: ['activeState', 'userId']
|
|
695
|
+
},
|
|
696
|
+
[QUEUE_ITEM]: {
|
|
697
|
+
data: {id: props.itemId}
|
|
698
|
+
// use an underscore here to tell resourcerer to spread the resulting object
|
|
699
|
+
provides: {_: getUserDataFromItem}
|
|
700
|
+
}
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
export default function QueueItemPage(props) {
|
|
704
|
+
// activeState and userId are internal state within `useResources` and returned
|
|
705
|
+
const {
|
|
706
|
+
activeState,
|
|
707
|
+
userId,
|
|
708
|
+
userModel,
|
|
709
|
+
queueItemModel
|
|
710
|
+
} = useResources(getResources, props);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function getUserDataFromItem(queueItemModel) {
|
|
714
|
+
// transform function now returns an object of prop names/values instead of a simple prop value
|
|
715
|
+
return {userId: queueItemModel.get('userId'), activeState: queueItemModel.get('state')};
|
|
716
|
+
}
|
|
717
|
+
```
|
|
683
718
|
|
|
684
719
|
# Differences between useResources and withResources
|
|
685
720
|
|
|
@@ -691,7 +726,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
|
|
|
691
726
|
|
|
692
727
|
```js
|
|
693
728
|
function MyComponent({start_time, ...props}) {
|
|
694
|
-
|
|
729
|
+
const {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {params: {start_time}}}), props);
|
|
695
730
|
|
|
696
731
|
// ...
|
|
697
732
|
```
|
|
@@ -700,7 +735,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
|
|
|
700
735
|
|
|
701
736
|
```js
|
|
702
737
|
function MyComponent(props) {
|
|
703
|
-
|
|
738
|
+
const {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
|
|
704
739
|
|
|
705
740
|
// ...
|
|
706
741
|
```
|
|
@@ -708,10 +743,10 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
|
|
|
708
743
|
or, even clearer, define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
|
|
709
744
|
|
|
710
745
|
```js
|
|
711
|
-
const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {
|
|
746
|
+
const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}});
|
|
712
747
|
|
|
713
748
|
function MyComponent(props) {
|
|
714
|
-
|
|
749
|
+
const {todosCollection} = useResources(getResources, props);
|
|
715
750
|
|
|
716
751
|
// ...
|
|
717
752
|
```
|
|
@@ -728,7 +763,7 @@ Again, it’s unlikely that you’ll use `ModelCache` directly while using `reso
|
|
|
728
763
|
|
|
729
764
|
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
765
|
|
|
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 [
|
|
766
|
+
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
767
|
|
|
733
768
|
2. A function, whose return value is an object of keys and values that should both contribute to the cache key.
|
|
734
769
|
|
|
@@ -740,7 +775,7 @@ const getResources = (ResourceKeys, props) => {
|
|
|
740
775
|
|
|
741
776
|
return {
|
|
742
777
|
[ResourceKeys.USER_TODOS]: {
|
|
743
|
-
|
|
778
|
+
params: {
|
|
744
779
|
limit: props.limit,
|
|
745
780
|
end_time: now,
|
|
746
781
|
start_time: now - props.timeRange,
|
|
@@ -756,12 +791,8 @@ And our corresponding model definition might look like this:
|
|
|
756
791
|
|
|
757
792
|
```js
|
|
758
793
|
export class UserTodosCollection extends Collection {
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
url() {
|
|
764
|
-
return `/users/${this.userId}/todos`;
|
|
794
|
+
url({userId}) {
|
|
795
|
+
return `/users/${userId}/todos`;
|
|
765
796
|
}
|
|
766
797
|
// ...
|
|
767
798
|
|
|
@@ -774,15 +805,15 @@ export class UserTodosCollection extends Collection {
|
|
|
774
805
|
};
|
|
775
806
|
```
|
|
776
807
|
|
|
777
|
-
We can see that `limit` and `sort_field` as specified in `cacheFields` are taken straight from the `
|
|
808
|
+
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
809
|
|
|
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—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 `
|
|
810
|
+
The time range is a little tougher to cache, though. We're less interested the spcecific `end_time`/`start_time` values to the millisecond—it does us little good to cache an endpoint tied to `Date.now()` when it will never be the same for the next request. We're much more interested in the difference between `end_time` and `start_time`. This is a great use-case for a function entry in `cacheFields`, which takes the `params` object passed an argument. In the case above, the returned object will contribute a key called `range` and a value equal to the time range to the cache key.
|
|
780
811
|
|
|
781
812
|
The generated cache key would be something like `userTodos_limit=50_$range=86400000_sort_field=importance_userId=noah`. Again, note that:
|
|
782
813
|
|
|
783
814
|
- the `userId` value is taken from the `options` hash
|
|
784
|
-
- the `limit` and `sort_field` values are taken from the `
|
|
785
|
-
- the `range` value is taken from a function that takes `start_millis`/`end_millis` from the `
|
|
815
|
+
- the `limit` and `sort_field` values are taken from the `params` hash
|
|
816
|
+
- the `range` value is taken from a function that takes `start_millis`/`end_millis` from the `params` hash into account.
|
|
786
817
|
|
|
787
818
|
|
|
788
819
|
## Prefetch on Hover
|
|
@@ -798,7 +829,7 @@ const getTodos = (ResourceKeys, props) => {
|
|
|
798
829
|
|
|
799
830
|
return {
|
|
800
831
|
[ResourceKeys.USER_TODOS]: {
|
|
801
|
-
|
|
832
|
+
params: {
|
|
802
833
|
limit: props.limit,
|
|
803
834
|
end_time: now,
|
|
804
835
|
start_time: now - props.timeRange,
|
|
@@ -828,7 +859,7 @@ It takes a function that is passed `ResourceKeys` and should return a list of `R
|
|
|
828
859
|
|
|
829
860
|
```js
|
|
830
861
|
function MyComponent(props) {
|
|
831
|
-
|
|
862
|
+
const {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
|
|
832
863
|
|
|
833
864
|
// ...
|
|
834
865
|
|
|
@@ -851,7 +882,7 @@ class MyMeasuredModel extends Model {
|
|
|
851
882
|
static measure = true
|
|
852
883
|
|
|
853
884
|
// or a function that returns a boolean, which will track instance requests based on a condition
|
|
854
|
-
static measure = ({
|
|
885
|
+
static measure = ({data={}}) => data.id === 'noahgrant'
|
|
855
886
|
}
|
|
856
887
|
```
|
|
857
888
|
|
|
@@ -910,10 +941,10 @@ ResourcesConfig.set(configObj);
|
|
|
910
941
|
import {stringify} from 'qs';
|
|
911
942
|
|
|
912
943
|
ResourcesConfig.set({
|
|
913
|
-
stringify(
|
|
914
|
-
//
|
|
944
|
+
stringify(params, options) {
|
|
945
|
+
// params is the params object to be stringified into query parameters
|
|
915
946
|
// options is the request options object
|
|
916
|
-
return stringify(
|
|
947
|
+
return stringify(params);
|
|
917
948
|
}
|
|
918
949
|
});
|
|
919
950
|
```
|
|
@@ -925,7 +956,7 @@ ResourcesConfig.set(configObj);
|
|
|
925
956
|
* the event string, `'API Fetch'`
|
|
926
957
|
* event data object with the following properties:
|
|
927
958
|
* Resource (string): the name of the resource (taken from the entry in `ResourceKeys`)
|
|
928
|
-
*
|
|
959
|
+
* params (object): params object supplied via the resource's config
|
|
929
960
|
* options (object): options object supplied via the resource's config
|
|
930
961
|
* duration (number): time in milliseconds between request and response
|
|
931
962
|
|
|
@@ -979,12 +1010,12 @@ ResourcesConfig.set(configObj);
|
|
|
979
1010
|
|
|
980
1011
|
// component1
|
|
981
1012
|
function MyComponent({category, ...props}) {
|
|
982
|
-
|
|
1013
|
+
const {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
|
|
983
1014
|
}
|
|
984
1015
|
|
|
985
1016
|
// component2--identical to the first
|
|
986
1017
|
function MyComponent({category, ...props}) {
|
|
987
|
-
|
|
1018
|
+
const {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
|
|
988
1019
|
}
|
|
989
1020
|
```
|
|
990
1021
|
|
|
@@ -1030,7 +1061,7 @@ ResourcesConfig.set(configObj);
|
|
|
1030
1061
|
|
|
1031
1062
|
return {
|
|
1032
1063
|
[ResourceKeys.USER_TODOS]: {
|
|
1033
|
-
|
|
1064
|
+
params: {
|
|
1034
1065
|
limit: 20,
|
|
1035
1066
|
end_time: now,
|
|
1036
1067
|
start_time: now - props.timeRange,
|
|
@@ -1046,7 +1077,7 @@ ResourcesConfig.set(configObj);
|
|
|
1046
1077
|
|
|
1047
1078
|
* Can `resourcerer` do anything other than `GET` requests?
|
|
1048
1079
|
|
|
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 `
|
|
1080
|
+
`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
1081
|
|
|
1051
1082
|
For write operations, use Models' [`save`](/docs/model.md#save) and [`destroy`](/docs/model.md#destroy) methods directly:
|
|
1052
1083
|
|