resourcerer 1.0.0-alpha-2 → 1.0.0-beta-3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +162 -124
- package/index.js +0 -6
- package/lib/collection.js +7 -0
- package/lib/model.js +9 -1
- package/lib/prefetch.js +2 -2
- package/lib/resourcerer.js +27 -332
- package/package.json +1 -1
- package/test/prefetch.test.js +1 -1
- package/test/sync.test.js +0 -1
- package/test/test-utils.js +0 -80
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
<img src="https://user-images.githubusercontent.com/1355779/61337603-f9fffd80-a7ea-11e9-9cb3-fa82e044c86e.png" alt="Resourcerer Icon" height="200" width="200" />
|
|
2
2
|
|
|
3
|
-
# resourcerer
|
|
3
|
+
# resourcerer (now in 1.0-beta!)
|
|
4
4
|
|
|
5
5
|
`resourcerer` is a library for declaratively fetching and caching your application's data. Its powerful [`useResources`](#useresources) React hook or [`withResources`](#withresources) higher-order React component (HOC) allows you to easily construct a component's data flow, including:
|
|
6
6
|
|
|
@@ -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:
|
|
@@ -47,7 +48,7 @@ ModelMap.add({TODOS: TodosCollection});
|
|
|
47
48
|
|
|
48
49
|
```js
|
|
49
50
|
// in your top level js file
|
|
50
|
-
import 'js/core/resourcerer-config;
|
|
51
|
+
import 'js/core/resourcerer-config';
|
|
51
52
|
```
|
|
52
53
|
|
|
53
54
|
3. Use your preferred abstraction (`useResources` hook or `withResources` HOC) to request your models in any component:
|
|
@@ -94,7 +95,7 @@ import 'js/core/resourcerer-config;
|
|
|
94
95
|
import React from 'react';
|
|
95
96
|
import {withResources} from 'resourcerer';
|
|
96
97
|
|
|
97
|
-
@withResources((
|
|
98
|
+
@withResources(({TODOS}, props) => ({[TODOS]: {}}))
|
|
98
99
|
class MyComponent extends React.Component {
|
|
99
100
|
render() {
|
|
100
101
|
// when MyComponent is mounted, the todosCollection is fetched and available
|
|
@@ -133,12 +134,12 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
|
|
|
133
134
|
1. [Other Common Resource Config Options](#other-common-resource-config-options)
|
|
134
135
|
1. [data](#data)
|
|
135
136
|
1. [options](#options)
|
|
136
|
-
1. [attributes](#attributes)
|
|
137
137
|
1. [noncritical](#noncritical)
|
|
138
138
|
1. [forceFetch](#forcefetch)
|
|
139
139
|
1. [Custom Resource Names](#custom-resource-names)
|
|
140
140
|
1. [prefetches](#prefetches)
|
|
141
|
-
1. [
|
|
141
|
+
1. [attributes](#attributes)
|
|
142
|
+
1. [Data mutations](#data-mutations)
|
|
142
143
|
1. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
|
|
143
144
|
1. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
|
|
144
145
|
1. [Declarative Cache Keys](#declarative-cache-keys)
|
|
@@ -153,7 +154,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
|
|
|
153
154
|
|
|
154
155
|
`$ npm i resourcerer`
|
|
155
156
|
|
|
156
|
-
`resourcerer` requires on React >= 16 but has no external dependencies.
|
|
157
|
+
`resourcerer` requires on React >= 16.8 but has no external dependencies.
|
|
157
158
|
|
|
158
159
|
Note that Resourcerer uses ES2015 in its source and does no transpiling—including import/export (Local babel configuration is for testing, only).
|
|
159
160
|
This means that if you're not babelifying your `node_modules` folder, you'll need to make an exception for this package, ie:
|
|
@@ -169,21 +170,11 @@ module: {
|
|
|
169
170
|
}
|
|
170
171
|
```
|
|
171
172
|
|
|
172
|
-
Also note that it also uses [legacy, Stage-1 decorators](https://github.com/tc39/proposal-decorators/blob/master/previous/METAPROGRAMMING.md), so you'll need to use the [babel decorators plugin](https://babeljs.io/docs/en/babel-plugin-proposal-decorators) with the `{legacy: true}` option:
|
|
173
|
-
|
|
174
|
-
```
|
|
175
|
-
// .babelrc
|
|
176
|
-
"plugins": [
|
|
177
|
-
["@babel/proposal-decorators", {"legacy": true}],
|
|
178
|
-
// ...
|
|
179
|
-
]
|
|
180
|
-
```
|
|
181
|
-
|
|
182
173
|
# Nomenclature
|
|
183
174
|
|
|
184
175
|
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.
|
|
185
176
|
|
|
186
|
-
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.
|
|
177
|
+
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.
|
|
187
178
|
|
|
188
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:
|
|
189
180
|
|
|
@@ -219,8 +210,9 @@ Also note that it also uses [legacy, Stage-1 decorators](https://github.com/tc39
|
|
|
219
210
|
Okay, back to the initial example. Let's take a look at our `useResources` usage in the component:
|
|
220
211
|
|
|
221
212
|
```js
|
|
222
|
-
// Note: in these docs, you will see a combination of `ResourceKeys` in the executor
|
|
223
|
-
// its more common destructured version, ie
|
|
213
|
+
// Note: in these docs, you will see a combination of `ResourceKeys` in the executor
|
|
214
|
+
// function as well as its more common destructured version, ie:
|
|
215
|
+
// `@withResources(({TODOS}, props) => ({[TODOS]: {}}))`
|
|
224
216
|
const getResources = (ResourceKeys, props) => ({[ResourceKeys.TODOS]: {}});
|
|
225
217
|
|
|
226
218
|
export default function MyComponent(props) {
|
|
@@ -231,7 +223,7 @@ export default function MyComponent(props) {
|
|
|
231
223
|
```
|
|
232
224
|
|
|
233
225
|
You see that `useResources` takes an executor function that returns an object. The executor function
|
|
234
|
-
takes two arguments:
|
|
226
|
+
takes two arguments: an object of `ResourceKeys` and the current props. Where does `ResourceKeys` come
|
|
235
227
|
from? From the ModelMap in the config file we added to earlier!
|
|
236
228
|
|
|
237
229
|
```js
|
|
@@ -248,15 +240,15 @@ ModelMap.add({TODOS: TodosCollection});
|
|
|
248
240
|
|
|
249
241
|
(We can also pass custom prefixes for our prop names in a component, but [we'll get to that later](#custom-resource-names).)
|
|
250
242
|
|
|
251
|
-
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
|
|
243
|
+
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.
|
|
252
244
|
|
|
253
245
|
|
|
254
246
|
## Other Props Returned from the Hook/Passed from the HOC (Loading States)
|
|
255
247
|
|
|
256
|
-
Of course, in our initial example, the
|
|
248
|
+
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—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:
|
|
257
249
|
|
|
258
250
|
|
|
259
|
-
- `todosLoadingState` (can be equal to any of the [LoadingStates constants](https://github.com/noahgrant/resourcerer/blob/master/lib/constants.js)
|
|
251
|
+
- `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`)
|
|
260
252
|
- `hasLoaded` {boolean} - all critical resources have successfully completed and are ready to be used by the component
|
|
261
253
|
- `isLoading` {boolean} - any of the critical resources are still in the process of being fetched
|
|
262
254
|
- `hasErrored` {boolean} - any of the critical resource requests did not complete successfully
|
|
@@ -264,7 +256,7 @@ Of course, in our initial example, the todos collection won’t get passed down
|
|
|
264
256
|
`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—a small piece of the overall component and not worth delaying render over. Here’s how we do that:
|
|
265
257
|
|
|
266
258
|
```js
|
|
267
|
-
const getResources = ({TODOS,
|
|
259
|
+
const getResources = ({TODOS, USERS}, props) => ({
|
|
268
260
|
[TODOS]: {},
|
|
269
261
|
[USERS]: {noncritical: true}
|
|
270
262
|
});
|
|
@@ -316,7 +308,8 @@ function MyClassWithTodosAndAUsers(props) {
|
|
|
316
308
|
|
|
317
309
|
{hasLoaded ? (
|
|
318
310
|
// at this point we are guaranteed all critical resources have returned.
|
|
319
|
-
// before that, todosCollection is a Collection instance
|
|
311
|
+
// before that, todosCollection is still a Collection instance that can be
|
|
312
|
+
// mapped over--it's just empty
|
|
320
313
|
<ul>
|
|
321
314
|
{todosCollection.map((todoModel) => (
|
|
322
315
|
<li key={todoModel.id}>
|
|
@@ -345,7 +338,7 @@ And here's what it looks like when the stats endpoint returns:
|
|
|
345
338
|
|
|
346
339
|

|
|
347
340
|
|
|
348
|
-
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:
|
|
341
|
+
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.
|
|
349
342
|
|
|
350
343
|
|
|
351
344
|
## Requesting Prop-driven Data
|
|
@@ -383,13 +376,13 @@ export default class UserModel extends Model {
|
|
|
383
376
|
}
|
|
384
377
|
```
|
|
385
378
|
|
|
386
|
-
The `cacheFields` static property is important here, as we'll see in a second; it is a list of
|
|
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:
|
|
387
380
|
|
|
388
|
-
1. the `options` object
|
|
389
|
-
1. the `attributes` object
|
|
390
|
-
1. the `data`
|
|
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
|
|
391
384
|
|
|
392
|
-
All three of these come from
|
|
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:
|
|
393
386
|
|
|
394
387
|
```jsx
|
|
395
388
|
const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}})
|
|
@@ -417,17 +410,17 @@ In general, there are two ways to change `props.id` as in the previous example:
|
|
|
417
410
|
|
|
418
411
|
1. Change the url, which is the top-most state-carrying entity of any application. The url can be changed either by path parameter or query paramter, i.e. `example.com/users/noahgrant` -> `example.com/users/fredsadaghiani`, or `example.com/users?id=noahgrant` -> `example.com/users?id=fredsadaghiani`. In this case, each prop change is _indexable_, which is sometimes desirable, sometimes not.
|
|
419
412
|
|
|
420
|
-
1. Change internal application state. For these cases, `useResources`/`withResources` make available another handy prop: `setResourceState`. `setResourceState` is a function that has the same method signature as the `
|
|
413
|
+
1. Change internal application state. For these cases, `useResources`/`withResources` make available another handy prop: `setResourceState`. `setResourceState` is a function that has the same method signature as the `useState` we all know and love. It sets internal hook/HOC state, which is then returned/passed down, respectively, overriding any initial prop, ie `setResourceState((state) => ({...state, id: 'fredsadaghiani'}))`. This is _not_ indexable.
|
|
421
414
|
|
|
422
|
-
Note that `setResourceState`
|
|
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.
|
|
423
416
|
|
|
424
417
|
|
|
425
418
|
## Serial Requests
|
|
426
419
|
|
|
427
|
-
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.
|
|
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.
|
|
428
421
|
|
|
429
422
|
```js
|
|
430
|
-
@withResources((
|
|
423
|
+
@withResources(({QUEUE_ITEM, USER}, props) => ({
|
|
431
424
|
[USER]: {
|
|
432
425
|
options: {userId: props.userId},
|
|
433
426
|
dependsOn: ['userId']
|
|
@@ -446,7 +439,7 @@ function getUserIdFromItem(queueItemModel) {
|
|
|
446
439
|
|
|
447
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.
|
|
448
441
|
|
|
449
|
-
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
|
|
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!
|
|
450
443
|
|
|
451
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).
|
|
452
445
|
|
|
@@ -486,10 +479,10 @@ function getUserDataFromItem(queueItemModel) {
|
|
|
486
479
|
|
|
487
480
|
### data
|
|
488
481
|
|
|
489
|
-
The `data` option is passed directly to the [sync](/docs/model.md#sync)
|
|
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:
|
|
490
483
|
|
|
491
484
|
```js
|
|
492
|
-
@withResources((
|
|
485
|
+
@withResources((ResourceKeys, props) => {
|
|
493
486
|
const now = Date.now();
|
|
494
487
|
|
|
495
488
|
return {
|
|
@@ -532,11 +525,7 @@ const getResources = (ResourceKeys, props) => {
|
|
|
532
525
|
};
|
|
533
526
|
```
|
|
534
527
|
|
|
535
|
-
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.
|
|
536
|
-
|
|
537
|
-
### attributes
|
|
538
|
-
|
|
539
|
-
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).
|
|
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}`).
|
|
540
529
|
|
|
541
530
|
|
|
542
531
|
### noncritical
|
|
@@ -554,7 +543,7 @@ As alluded to in the [Other Props](#other-props-returned-from-the-hookpassed-fro
|
|
|
554
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 `forceFetch: 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 `forceFetch: true` request for the resource.
|
|
555
544
|
|
|
556
545
|
```js
|
|
557
|
-
@withResources((
|
|
546
|
+
@withResources((ResourceKeys, props) => ({[ResourceKeys.LATEST_STATS]: {forceFetch: true}}))
|
|
558
547
|
class MyComponentWithLatestStats extends React.Component {}
|
|
559
548
|
```
|
|
560
549
|
|
|
@@ -615,38 +604,90 @@ When the user clicks on a 'next' arrow that updates page state, the collection w
|
|
|
615
604
|
|
|
616
605
|
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.
|
|
617
606
|
|
|
618
|
-
###
|
|
619
|
-
##### *(`withResources` only)*
|
|
607
|
+
### attributes
|
|
620
608
|
|
|
621
|
-
|
|
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.
|
|
622
610
|
|
|
623
|
-
|
|
624
|
-
@withResources((props, ResourceKeys) => ({
|
|
625
|
-
[ResourceKeys.TODOS]: {measure: true, status: true}
|
|
626
|
-
}))
|
|
627
|
-
class MyComponentWithTodos extends React.Component {}
|
|
628
|
-
```
|
|
611
|
+
# Data Mutations
|
|
629
612
|
|
|
630
|
-
|
|
613
|
+
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:
|
|
631
614
|
|
|
632
|
-
#
|
|
615
|
+
1. [Model#save](/docs/model.md#save)
|
|
633
616
|
|
|
634
|
-
|
|
617
|
+
Use this to create a new resource object (POST) or update an existing one (PUT). Uses the return value of the [`isNew()`](/docs/model.md#isNew) method to determine which method to use. If updating, pass a `{patch: true}` option to use PATCH instead of PUT, which will also send over only the changed attributes instead of the entire resource.
|
|
635
618
|
|
|
636
|
-
|
|
619
|
+
```js
|
|
620
|
+
function MyComponent(props) {
|
|
621
|
+
var {myModel} = useResources(getResources, props),
|
|
622
|
+
onSave = () => myModel.save({foo: 'bar'})
|
|
623
|
+
.then([model]) => // ...)
|
|
624
|
+
.catch(() => alert('request failed'));
|
|
625
|
+
|
|
626
|
+
return <button onClick={onSave}>Persist model</button>;
|
|
627
|
+
}
|
|
628
|
+
```
|
|
637
629
|
|
|
638
|
-
1.
|
|
630
|
+
1. [Model#destroy](/docs/model.md#destroy)
|
|
639
631
|
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
}));
|
|
632
|
+
Use this to make a DELETE request at a url with this model's id. Will also remove the model from any collection it is a part of.
|
|
633
|
+
|
|
634
|
+
```js
|
|
635
|
+
myModel.destroy().catch(() => alert('Model could not be destroyed));
|
|
645
636
|
```
|
|
646
637
|
|
|
647
|
-
1.
|
|
638
|
+
1. [Collection#create](/docs/collection.md#create)
|
|
648
639
|
|
|
649
|
-
|
|
640
|
+
If working with a collection instead of a model, `.create()` adds a new model to the collection and then persists it to the server (via `model.save()`). This is pretty convenient:
|
|
641
|
+
|
|
642
|
+
```js
|
|
643
|
+
function TodoDetails(props) {
|
|
644
|
+
var {hasLoaded, todosCollection} = useResources(getResources, props),
|
|
645
|
+
todoModel = todosCollection.get(props.id),
|
|
646
|
+
|
|
647
|
+
onSaveTodo = {
|
|
648
|
+
// set some loading state...
|
|
649
|
+
|
|
650
|
+
if (!props.id) {
|
|
651
|
+
// create new todo!
|
|
652
|
+
return todosCollection.create(attrs)
|
|
653
|
+
.then(([model]) => // ...)
|
|
654
|
+
.catch(() => alert('create failed'));
|
|
655
|
+
.then(() => // remove loading state);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// update existing
|
|
659
|
+
todoModel.save(attrs).then(([model]) => ...).catch(() => alert('update failed'));
|
|
660
|
+
};
|
|
661
|
+
|
|
662
|
+
if (hasLoaded && props.id && !todoModel) {
|
|
663
|
+
return <p>Todo not found.</p>;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
return (
|
|
667
|
+
// ...
|
|
668
|
+
<button onClick={onSaveTodo}>Save</button>
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
```
|
|
672
|
+
|
|
673
|
+
Each one of these methods exhibit the following behaviors:
|
|
674
|
+
|
|
675
|
+
1. They automatically fire off the appropriate request with the right data and at the right url
|
|
676
|
+
1. They will cause every component registered to that resource to re-render with the updated data, keeping the application in sync
|
|
677
|
+
1. On error, they undo the changes that were done (and their registered components render again).
|
|
678
|
+
|
|
679
|
+
**Note:**
|
|
680
|
+
1. All calls resolve an array, which is a tuple of [model, response]. All reject with just the response.
|
|
681
|
+
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.
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
# Differences between useResources and withResources
|
|
685
|
+
|
|
686
|
+
The hook and HOC largely operate interchangeably, but do note a couple critical differences:
|
|
687
|
+
|
|
688
|
+
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.
|
|
689
|
+
|
|
690
|
+
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:
|
|
650
691
|
|
|
651
692
|
```js
|
|
652
693
|
function MyComponent({start_time, ...props}) {
|
|
@@ -664,7 +705,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
|
|
|
664
705
|
// ...
|
|
665
706
|
```
|
|
666
707
|
|
|
667
|
-
or define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
|
|
708
|
+
or, even clearer, define your executor function outside of the component scope, as we've done throughout this tutorial (now you know why!):
|
|
668
709
|
|
|
669
710
|
```js
|
|
670
711
|
const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {data: {start_time}}});
|
|
@@ -735,7 +776,7 @@ export class UserTodosCollection extends Collection {
|
|
|
735
776
|
|
|
736
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.
|
|
737
778
|
|
|
738
|
-
The time range is a little tougher to cache, though. We're less interested the spcecific `end_time`/`start_time` values to the millisecond—
|
|
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 `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.
|
|
739
780
|
|
|
740
781
|
The generated cache key would be something like `userTodos_limit=50_$range=86400000_sort_field=importance_userId=noah`. Again, note that:
|
|
741
782
|
|
|
@@ -752,7 +793,7 @@ You can use `resourcerer`'s executor function to optimistically prefetch resourc
|
|
|
752
793
|
import {prefetch} from 'resourcerer';
|
|
753
794
|
|
|
754
795
|
// here's our executor function just as we pass to useResources or withResources
|
|
755
|
-
const getTodos = (
|
|
796
|
+
const getTodos = (ResourceKeys, props) => {
|
|
756
797
|
const now = Date.now();
|
|
757
798
|
|
|
758
799
|
return {
|
|
@@ -832,54 +873,54 @@ ResourcesConfig.set(configObj);
|
|
|
832
873
|
|
|
833
874
|
* `errorBoundaryChild` (JSX/React.Element): the element or component that should be rendered in the ErrorBoundary included in every `withResources` wrapping. By default, a caught error renders this child:
|
|
834
875
|
|
|
835
|
-
```jsx
|
|
836
|
-
<div className='caught-error'>
|
|
837
|
-
|
|
838
|
-
</div>
|
|
839
|
-
```
|
|
876
|
+
```jsx
|
|
877
|
+
<div className='caught-error'>
|
|
878
|
+
<p>An error occurred.</p>
|
|
879
|
+
</div>
|
|
880
|
+
```
|
|
840
881
|
|
|
841
882
|
* `log` (function): method invoked when an error is caught by the ErrorBoundary. Takes the caught error as an argument. Use this hook to send caught errors to your error monitoring system. **Default:** noop.
|
|
842
883
|
|
|
843
884
|
* `prefilter` (function): this function takes in the options object passed to the request and should return any new options you want to add. this is a great place to add custom request headers (like auth headers) or do custom error response handling. For example:
|
|
844
885
|
|
|
845
|
-
```js
|
|
846
|
-
prefilter: (options) => ({
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
886
|
+
```js
|
|
887
|
+
prefilter: (options) => ({
|
|
888
|
+
error: (response) => {
|
|
889
|
+
if (response.status === 401) {
|
|
890
|
+
// refresh auth token logic
|
|
891
|
+
} else if (response.status === 429) {
|
|
892
|
+
// do some rate-limiting retry logic
|
|
893
|
+
}
|
|
853
894
|
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
})
|
|
862
|
-
```
|
|
895
|
+
// catch callbacks still get called after this, so always default to rejecting
|
|
896
|
+
return Promise.reject(response);
|
|
897
|
+
},
|
|
898
|
+
headers: {
|
|
899
|
+
...options.headers,
|
|
900
|
+
Authorization: `Bearer ${localStorage.getItem('super-secret-auth-token')}`
|
|
901
|
+
}
|
|
902
|
+
})
|
|
903
|
+
```
|
|
863
904
|
|
|
864
|
-
**Default:** the identity function.
|
|
905
|
+
**Default:** the identity function.
|
|
865
906
|
|
|
866
|
-
* `stringify` (function): Use this to pass in a custom or more powerful way to stringify your GET parameters. The default is to use [URLSearchParams](), but that won't url-encode nested objects or arrays. Override this method if you need support for that, ie:
|
|
907
|
+
* `stringify` (function): Use this to pass in a custom or more powerful way to stringify your GET parameters. The default is to use [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams), but that won't url-encode nested objects or arrays. Override this method if you need support for that, ie:
|
|
867
908
|
|
|
868
|
-
```js
|
|
869
|
-
import {stringify} from 'qs';
|
|
909
|
+
```js
|
|
910
|
+
import {stringify} from 'qs';
|
|
870
911
|
|
|
871
|
-
ResourcesConfig.set({
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
});
|
|
878
|
-
```
|
|
912
|
+
ResourcesConfig.set({
|
|
913
|
+
stringify(data, options) {
|
|
914
|
+
// data is the data object to be stringified into query parameters
|
|
915
|
+
// options is the request options object
|
|
916
|
+
return stringify(data);
|
|
917
|
+
}
|
|
918
|
+
});
|
|
919
|
+
```
|
|
879
920
|
|
|
880
921
|
* `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'`.
|
|
881
922
|
|
|
882
|
-
* `track` (function): method invoked when [`measure
|
|
923
|
+
* `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:
|
|
883
924
|
|
|
884
925
|
* the event string, `'API Fetch'`
|
|
885
926
|
* event data object with the following properties:
|
|
@@ -903,19 +944,19 @@ ResourcesConfig.set({
|
|
|
903
944
|
React Query is an awesome popular library that shares some of the same features as resourcerer. But because `resourcerer` is _explicitly_ for REST APIs and React Query is backend agnostic, we get to abstract out even more. For example, in React Query, you'll need to imperatively fetch your resource in each component:
|
|
904
945
|
|
|
905
946
|
```js
|
|
906
|
-
// React Query
|
|
947
|
+
// React Query, assuming a made-up category dependency
|
|
907
948
|
// component 1
|
|
908
|
-
function MyComponent(props) {
|
|
949
|
+
function MyComponent({category, ...props}) {
|
|
909
950
|
// define your fetch key and imperatively fetch your resource
|
|
910
|
-
|
|
951
|
+
const {data} = useQuery(['somekey', {category}], () => {
|
|
911
952
|
return fetch('/todos', (res) => res.json())
|
|
912
953
|
}
|
|
913
954
|
}
|
|
914
955
|
|
|
915
956
|
// component 2
|
|
916
|
-
function MySecondComponent(props) {
|
|
957
|
+
function MySecondComponent({category, ...props}) {
|
|
917
958
|
// same thing. you'll probably want to abstract these out so that changing it one place changes it everywhere
|
|
918
|
-
|
|
959
|
+
const {data} = useQuery(['somekey', {category}], () => {
|
|
919
960
|
return fetch('/todos', (res) => res.json())
|
|
920
961
|
}
|
|
921
962
|
}
|
|
@@ -924,10 +965,11 @@ ResourcesConfig.set({
|
|
|
924
965
|
With resourcerer, this abstraction is done once in a model--both defining its url as well as how its properties should affect its cache key:
|
|
925
966
|
|
|
926
967
|
```js
|
|
927
|
-
// resourcerer
|
|
968
|
+
// resourcerer, with the same category dependency. dependencies are resource-specific,
|
|
969
|
+
// not component-specific, so they should be defined on the model instead of the component
|
|
928
970
|
// todos-collection.js
|
|
929
971
|
export default class TodosCollection extends Collection {
|
|
930
|
-
static cacheFields = ['
|
|
972
|
+
static cacheFields = ['category']
|
|
931
973
|
|
|
932
974
|
url() {
|
|
933
975
|
return '/todos';
|
|
@@ -936,17 +978,20 @@ ResourcesConfig.set({
|
|
|
936
978
|
|
|
937
979
|
|
|
938
980
|
// component1
|
|
939
|
-
function MyComponent(props) {
|
|
940
|
-
var {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {}}));
|
|
981
|
+
function MyComponent({category, ...props}) {
|
|
982
|
+
var {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
|
|
941
983
|
}
|
|
942
984
|
|
|
943
985
|
// component2--identical to the first
|
|
944
|
-
function
|
|
945
|
-
var {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {}}));
|
|
986
|
+
function MyComponent({category, ...props}) {
|
|
987
|
+
var {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
|
|
946
988
|
}
|
|
947
989
|
```
|
|
948
990
|
|
|
949
|
-
|
|
991
|
+
The other big difference you might note is the data object in the hook's response. With React Query, you get exactly the JSON returned by the server. With resourcerer, you get [Model](/docs/model.md) or [Collection](/docs/collection.md) instances, which are enriched data representations from which you can also perform write operations that will propagate throughout all other subscribed components—regardless of their location in your application. Need to update a model? Call [`model.set()`](/docs/model.md#set)—any other component that uses that model (or its collection) will automatically update. Need to persist to the server? Call [`model.save()`](/docs/model.md#save) or [`collection.add()`](/docs/collection.md#add). Need to remove the model? [`model.destroy()`](/docs/model.md#destroy). Ez-pz.
|
|
992
|
+
|
|
993
|
+
|
|
994
|
+
Also note that the `todosCollection` in both components 1 and 2 in the last example are the same objects.
|
|
950
995
|
|
|
951
996
|
|
|
952
997
|
* Does `resourcerer` support SSR?
|
|
@@ -956,13 +1001,6 @@ ResourcesConfig.set({
|
|
|
956
1001
|
1. passes instantiated models directly through the app before calling `renderToString`
|
|
957
1002
|
2. provides those models within a top-level `<script>` element that adds them directly to the [ModelCache](#caching-resources-with-modelcache).
|
|
958
1003
|
|
|
959
|
-
* Does it support async rendering?
|
|
960
|
-
|
|
961
|
-
Yes! `withResources` used to depend on `componentWillReceiveProps`, but as of v0.9 it has been updated to use `componentDidUpdate` instead.
|
|
962
|
-
The upside is that it now supports async rendering; the downside, however, is that it requires an extra render before updating a resource
|
|
963
|
-
(since `componentDidUpdate` gets called after `render`, setting any loading states will cause an additional subsequent render).
|
|
964
|
-
|
|
965
|
-
`useResources` has always supported async rendering.
|
|
966
1004
|
|
|
967
1005
|
* Can the `withResources` HOC be used with both function components and class components?
|
|
968
1006
|
|
|
@@ -987,7 +1025,7 @@ ResourcesConfig.set({
|
|
|
987
1025
|
</div>
|
|
988
1026
|
);
|
|
989
1027
|
|
|
990
|
-
export withResources((
|
|
1028
|
+
export withResources((ResourceKeys, props) => {
|
|
991
1029
|
const now = Date.now();
|
|
992
1030
|
|
|
993
1031
|
return {
|
|
@@ -1035,7 +1073,7 @@ ResourcesConfig.set({
|
|
|
1035
1073
|
|
|
1036
1074
|
* How big is the `resourcerer` package?
|
|
1037
1075
|
|
|
1038
|
-
|
|
1076
|
+
Under 10kB gzipped. It has no dependencies.
|
|
1039
1077
|
|
|
1040
1078
|
* Semver?
|
|
1041
1079
|
|
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';
|
package/lib/collection.js
CHANGED
|
@@ -54,6 +54,13 @@ export default class Collection {
|
|
|
54
54
|
*/
|
|
55
55
|
static cacheFields = []
|
|
56
56
|
|
|
57
|
+
/**
|
|
58
|
+
* Use this to tell resourcerer to track this collection's request time via the `track` method
|
|
59
|
+
* added in the resourcerer configuration file. This can be a boolean or a function that returns a
|
|
60
|
+
* boolean. If the latter, it takes a the resource config object as an argument.
|
|
61
|
+
*/
|
|
62
|
+
static measure = false
|
|
63
|
+
|
|
57
64
|
/**
|
|
58
65
|
* Similar to the method for an individual model, this maps through each model in the collection
|
|
59
66
|
* and returns its data attributes.
|
package/lib/model.js
CHANGED
|
@@ -60,6 +60,13 @@ export default class Model {
|
|
|
60
60
|
*/
|
|
61
61
|
static defaults = {}
|
|
62
62
|
|
|
63
|
+
/**
|
|
64
|
+
* Use this to tell resourcerer to track this model's request time via the `track` method added
|
|
65
|
+
* in the resourcerer configuration file. This can be a boolean or a function that returns a
|
|
66
|
+
* boolean. If the latter, it takes a the resource config object as an argument.
|
|
67
|
+
*/
|
|
68
|
+
static measure = false
|
|
69
|
+
|
|
63
70
|
/**
|
|
64
71
|
* Returns a copy of the model's `attributes` object. Use this method to get the current entire
|
|
65
72
|
* server data representation.
|
|
@@ -254,7 +261,8 @@ export default class Model {
|
|
|
254
261
|
})
|
|
255
262
|
.catch((response) => {
|
|
256
263
|
if (!options.wait) {
|
|
257
|
-
|
|
264
|
+
// keep the clear silent so that we only render when we reset attributes
|
|
265
|
+
this.clear({silent: true}).set(previousAttributes, options);
|
|
258
266
|
} else {
|
|
259
267
|
this.attributes = previousAttributes;
|
|
260
268
|
}
|
package/lib/prefetch.js
CHANGED
|
@@ -13,14 +13,14 @@ const PREFETCH_TIMEOUT = 50;
|
|
|
13
13
|
*
|
|
14
14
|
* @param {function} getResources - function that takes props as an argument
|
|
15
15
|
* and should return a map of resources. Identical to those used in
|
|
16
|
-
* `withResources`
|
|
16
|
+
* `useResources`/`withResources`
|
|
17
17
|
* @param {object} expectedProps - props in the form expected when the resource
|
|
18
18
|
* would be needed
|
|
19
19
|
* @return {function} callback to be invoked onMouseEnter of appropriate DOM el
|
|
20
20
|
*/
|
|
21
21
|
export default (getResources, expectedProps={}) => {
|
|
22
22
|
var fetched,
|
|
23
|
-
resources = Object.entries(getResources(
|
|
23
|
+
resources = Object.entries(getResources(ResourceKeys, expectedProps) || {});
|
|
24
24
|
|
|
25
25
|
return (evt) => {
|
|
26
26
|
var {target} = evt,
|
package/lib/resourcerer.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import {hasErrored, hasLoaded, isLoading
|
|
1
|
+
import {hasErrored, hasLoaded, isLoading} from './utils';
|
|
2
2
|
import {ModelMap, ResourceKeys, ResourcesConfig, UnfetchedResources} from './config';
|
|
3
|
+
/* eslint-disable no-unused-vars */
|
|
3
4
|
import React, {useEffect, useReducer, useRef, useState} from 'react';
|
|
5
|
+
/* eslint-enable no-unused-vars */
|
|
4
6
|
|
|
5
7
|
import Collection from './collection';
|
|
6
8
|
import ErrorBoundary from './error-boundary';
|
|
@@ -13,52 +15,13 @@ import request from './request';
|
|
|
13
15
|
const SPREAD_PROVIDES_CHAR = '_';
|
|
14
16
|
|
|
15
17
|
/**
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* a url update that passes its query params down as props[queryParamsPropName].
|
|
19
|
-
* But it provides a setResourceState method to wrap any necessary state that
|
|
20
|
-
* may cause a resource update in DataCarrier's componentDidUpdate.
|
|
21
|
-
*/
|
|
22
|
-
const resourceState = (Component) =>
|
|
23
|
-
class ResourceStateWrapper extends React.Component {
|
|
24
|
-
constructor() {
|
|
25
|
-
super();
|
|
26
|
-
this.state = {};
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
setResourceState(newState={}, cb) {
|
|
30
|
-
this.setState(
|
|
31
|
-
typeof newState === 'function' ? (state) => newState(state) : {
|
|
32
|
-
...this.state,
|
|
33
|
-
...newState
|
|
34
|
-
},
|
|
35
|
-
cb
|
|
36
|
-
);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
render() {
|
|
40
|
-
return (
|
|
41
|
-
<Component
|
|
42
|
-
{...this.props}
|
|
43
|
-
// spread url params and merge with state. url should take priority
|
|
44
|
-
// over passed props (like defaultProps), but state should take
|
|
45
|
-
// precedence over all
|
|
46
|
-
{...this.props[ResourcesConfig.queryParamsPropName] || {}}
|
|
47
|
-
{...this.state}
|
|
48
|
-
setResourceState={this.setResourceState.bind(this)}
|
|
49
|
-
/>
|
|
50
|
-
);
|
|
51
|
-
}
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* The withResources decorator produces a Data Carrier component that handles
|
|
56
|
-
* several different data-related things for a component automatically:
|
|
18
|
+
* The useResources hook handles several different data-related things for a component
|
|
19
|
+
* automatically:
|
|
57
20
|
*
|
|
58
|
-
* 1. it fetches a component's resources
|
|
21
|
+
* 1. it fetches a component's resources after mounting
|
|
59
22
|
* 2. it binds listeners to all resources
|
|
60
23
|
* 3. it handles whether or not the critical resources for a component have loaded
|
|
61
|
-
* 4. it re-fetches a new resource
|
|
24
|
+
* 4. it re-fetches a new resource when specified props have changed
|
|
62
25
|
* 5. it handles resource cache naming for the ModelCache
|
|
63
26
|
*
|
|
64
27
|
* getResources is a function that takes props as an argument and should return
|
|
@@ -81,8 +44,6 @@ const resourceState = (Component) =>
|
|
|
81
44
|
* a value to be set for the prop. If the key is equal to
|
|
82
45
|
* SPREAD_PROVIDES_CHAR, then the return value of the transform function
|
|
83
46
|
* is spread for dynamically-provided props.
|
|
84
|
-
* * status {boolean} - whether the component requires the status of the http
|
|
85
|
-
* request to be passed along.
|
|
86
47
|
* * prefetch {object} - an individual map of expected future props to fetch
|
|
87
48
|
* a new resource and store it in the cache. it will not, however, get
|
|
88
49
|
* passed down to the child (no loading states, either)
|
|
@@ -94,287 +55,6 @@ const resourceState = (Component) =>
|
|
|
94
55
|
* fetched and cached
|
|
95
56
|
* * ...any other option that can be passed directly to the `request` function
|
|
96
57
|
*/
|
|
97
|
-
export const withResources = (getResources) =>
|
|
98
|
-
(Component) => {
|
|
99
|
-
@resourceState
|
|
100
|
-
class DataCarrier extends React.Component {
|
|
101
|
-
constructor(props) {
|
|
102
|
-
super();
|
|
103
|
-
|
|
104
|
-
let resources = this._generateResources(props);
|
|
105
|
-
let initialLoadingStates = buildResourcesLoadingState(
|
|
106
|
-
resources.filter(withoutPrefetch),
|
|
107
|
-
props
|
|
108
|
-
);
|
|
109
|
-
|
|
110
|
-
this.prevPropsRef = React.createRef({});
|
|
111
|
-
|
|
112
|
-
// set initial loading state for our resources
|
|
113
|
-
this.state = {
|
|
114
|
-
// our models kept as state. in the past they were not, and they were only read directly
|
|
115
|
-
// from the cache. this works and is super clean, but a big downside is that there is a
|
|
116
|
-
// lot you have to juggle to show a model based on prevProps when props have changed.
|
|
117
|
-
// this is ultimately just simpler, despite the denormalization
|
|
118
|
-
...resources.filter(withoutPrefetch).reduce((models, [name, config]) => ({
|
|
119
|
-
...models,
|
|
120
|
-
[getResourcePropertyName(name, config.modelKey)]: getModelFromCache(config) ||
|
|
121
|
-
getEmptyModel(config)
|
|
122
|
-
}), {}),
|
|
123
|
-
...initialLoadingStates,
|
|
124
|
-
/**
|
|
125
|
-
* Whether our critical resources have been loaded a first time. Useful for showing
|
|
126
|
-
* reflecting a different UI for subsequent requests
|
|
127
|
-
*/
|
|
128
|
-
hasInitiallyLoaded: hasLoaded(getCriticalLoadingStates(initialLoadingStates, resources))
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
componentDidMount() {
|
|
133
|
-
var resources = this._generateResources()
|
|
134
|
-
.filter(hasAllDependencies.bind(null, this.props))
|
|
135
|
-
.filter(not(shouldBypassFetch.bind(null, this.props)));
|
|
136
|
-
|
|
137
|
-
// fetch models
|
|
138
|
-
this._fetchResources(resources);
|
|
139
|
-
this._isMounted = true;
|
|
140
|
-
|
|
141
|
-
this._attachModelListeners();
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
componentDidUpdate(prevProps) {
|
|
145
|
-
// update models based on new props or new resources
|
|
146
|
-
var nextResources = this._generateResources(),
|
|
147
|
-
pendingResources = nextResources.filter(not(hasAllDependencies.bind(null, this.props)))
|
|
148
|
-
.filter(([, config]) => hasAllDependencies(prevProps, [, config])),
|
|
149
|
-
resourcesToUpdate = this._getResourcesToUpdate(nextResources, prevProps),
|
|
150
|
-
nextLoadingStates = {
|
|
151
|
-
...buildResourcesLoadingState(pendingResources, this.props, LoadingStates.PENDING),
|
|
152
|
-
// but resourcesToUpdate should get set to LOADING (or LOADED if in the cache)
|
|
153
|
-
...buildResourcesLoadingState(resourcesToUpdate.filter(withoutPrefetch), this.props)
|
|
154
|
-
},
|
|
155
|
-
|
|
156
|
-
// separate out those resources to update into those that are already cached and those
|
|
157
|
-
// that need to be fetched. the former will get the models updated immediately
|
|
158
|
-
[loadedResources, resourcesToFetch] = partitionResources(
|
|
159
|
-
resourcesToUpdate,
|
|
160
|
-
nextLoadingStates
|
|
161
|
-
);
|
|
162
|
-
|
|
163
|
-
// first set our updated resources' loading states to LOADING. also, any
|
|
164
|
-
// resources that have lost their dependencies should go back to a pending state
|
|
165
|
-
// and their models reverted to the empty models. new resources that have already
|
|
166
|
-
// been loaded should be set to LOADED with their cached models set as state immediately
|
|
167
|
-
if (pendingResources.length || resourcesToUpdate.length) {
|
|
168
|
-
this.setState({
|
|
169
|
-
...pendingResources.concat(loadedResources).filter(withoutPrefetch)
|
|
170
|
-
.reduce((memo, [name, config]) => Object.assign(memo, {
|
|
171
|
-
// if pending resource cache key doesn't change, don't reset it to empty
|
|
172
|
-
[getResourcePropertyName(name, config.modelKey)]: getModelFromCache(config) ||
|
|
173
|
-
getEmptyModel(config)
|
|
174
|
-
}), {}),
|
|
175
|
-
...nextLoadingStates
|
|
176
|
-
});
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
resourcesToFetch.forEach(([name, config]) => {
|
|
180
|
-
var previousConfig = findConfig([name, config], getResources, prevProps),
|
|
181
|
-
previousCacheKey = this._findCurrentCacheKey([name, config], prevProps);
|
|
182
|
-
|
|
183
|
-
// unregister component from previous models that are getting updated
|
|
184
|
-
ModelCache.unregister(this, previousCacheKey);
|
|
185
|
-
|
|
186
|
-
// this is our re-caching: if we already have a new model in the cache that has now been
|
|
187
|
-
// saved (and thus has a real cache key), move the model to the new cache key and remove
|
|
188
|
-
// it from the old one. this will save an unnecessary request.
|
|
189
|
-
if (previousConfig.attributes && !previousConfig.attributes.id && config.attributes?.id) {
|
|
190
|
-
ModelCache.put(getCacheKey(config), ModelCache.get(previousCacheKey));
|
|
191
|
-
ModelCache.remove(previousCacheKey);
|
|
192
|
-
}
|
|
193
|
-
});
|
|
194
|
-
|
|
195
|
-
if (resourcesToFetch.length) {
|
|
196
|
-
this._fetchResources(resourcesToFetch);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
if ((this.props.refetches || []).length) {
|
|
200
|
-
this.props.setResourceState((state) => ({...state, refetches: []}));
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
this.prevPropsRef.current = this.props;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
componentWillUnmount() {
|
|
207
|
-
this._isMounted = false;
|
|
208
|
-
this._unattachModelListeners.call(this);
|
|
209
|
-
ModelCache.unregister(this);
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
_fetchResources(resources, props=this.props) {
|
|
213
|
-
return fetchResources(resources, props, {
|
|
214
|
-
component: this,
|
|
215
|
-
isCurrentResource: ([name, config], cacheKey) => this._isMounted && !config.prefetch &&
|
|
216
|
-
cacheKey === this._findCurrentCacheKey([name, config]),
|
|
217
|
-
setResourceState: props.setResourceState,
|
|
218
|
-
onRequestSuccess: (model, status, [name, config]) => {
|
|
219
|
-
// set loading state _after_ all its dependencies are added
|
|
220
|
-
this.setState((state) => {
|
|
221
|
-
var nextState = {
|
|
222
|
-
...state,
|
|
223
|
-
[getResourceState(name)]: LoadingStates.LOADED,
|
|
224
|
-
[getResourcePropertyName(name, config.modelKey)]: model,
|
|
225
|
-
...(config.status ? {[getResourceStatus(name)]: status} : {})
|
|
226
|
-
};
|
|
227
|
-
|
|
228
|
-
return {
|
|
229
|
-
...nextState,
|
|
230
|
-
// if we haven't already loaded and this response gets us into the loaded state
|
|
231
|
-
// across our critical resources, set the hasInitiallyLoaded flag
|
|
232
|
-
...!this.state.hasInitiallyLoaded &&
|
|
233
|
-
hasLoaded(getCriticalLoadingStates(nextState, resources)) ?
|
|
234
|
-
{hasInitiallyLoaded: true} : {}
|
|
235
|
-
};
|
|
236
|
-
});
|
|
237
|
-
},
|
|
238
|
-
onRequestFailure: (status, [name, config]) => {
|
|
239
|
-
// this catch block gets called _only_ for request errors
|
|
240
|
-
this.setState({
|
|
241
|
-
[getResourceState(name)]: LoadingStates.ERROR,
|
|
242
|
-
...(config.status ? {[getResourceStatus(name)]: status} : {})
|
|
243
|
-
});
|
|
244
|
-
}
|
|
245
|
-
}).then(() => {
|
|
246
|
-
if (this._isMounted) {
|
|
247
|
-
// attaches listeners on all resources (removes any existing first)
|
|
248
|
-
this._attachModelListeners();
|
|
249
|
-
}
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
_getResourcesToUpdate(resources, prevProps) {
|
|
254
|
-
return resources.filter(hasAllDependencies.bind(null, this.props))
|
|
255
|
-
.filter(not(shouldBypassFetch.bind(null, this.props)))
|
|
256
|
-
.filter(([name, config]) =>
|
|
257
|
-
this._hasResourceConfigChanged(name, config, prevProps) ||
|
|
258
|
-
!hasAllDependencies(prevProps, [, config]) || config.refetch);
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
_generateResources(props=this.props) {
|
|
262
|
-
return generateResources(getResources, props);
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
_findCurrentCacheKey(resource, props=this.props) {
|
|
266
|
-
return findCacheKey(resource, getResources, props);
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
/**
|
|
270
|
-
* This method determines whether a resource's config has changed between
|
|
271
|
-
* this.props and prevProps. We compare cache key strings for this.props/prevProps
|
|
272
|
-
*
|
|
273
|
-
* @param {string} name - resource name
|
|
274
|
-
* @param {object} config - resource config object
|
|
275
|
-
* @param {object} prevProps - component's prevProps, used to compare
|
|
276
|
-
* cache keys with current props
|
|
277
|
-
* @return {boolean} whether a resource's config has changed between
|
|
278
|
-
* this.props and prevProps, which will prompt a refetch
|
|
279
|
-
*/
|
|
280
|
-
_hasResourceConfigChanged(name, config, prevProps) {
|
|
281
|
-
var currentCacheKey = this._findCurrentCacheKey([name, config]),
|
|
282
|
-
previousCacheKey = this._findCurrentCacheKey([name, config], prevProps);
|
|
283
|
-
|
|
284
|
-
// currentCacheKey won't exist if the current resource is a prefetched resource,
|
|
285
|
-
// which we don't want to consider for determining a changed config
|
|
286
|
-
return !currentCacheKey || currentCacheKey !== previousCacheKey;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
// NOTE: this must be bound here to keep React.memo working when shallow-comparing props
|
|
290
|
-
_refetch = (fn) => {
|
|
291
|
-
var refetches = fn(ResourceKeys);
|
|
292
|
-
|
|
293
|
-
if (refetches.length) {
|
|
294
|
-
this.props.setResourceState((state) => ({...state, refetches}));
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
_onModelEvent() {
|
|
299
|
-
this.forceUpdate();
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
_attachModelListeners() {
|
|
303
|
-
var modelsToAttach = this._generateResources()
|
|
304
|
-
.map(([, config]) => getModelFromCache(config))
|
|
305
|
-
.filter(Boolean);
|
|
306
|
-
|
|
307
|
-
// unattach any previously-attached listeners first
|
|
308
|
-
this._unattachModelListeners();
|
|
309
|
-
|
|
310
|
-
// whenever there may be a change in the data, trigger a React update.
|
|
311
|
-
modelsToAttach.forEach((model) => model.onUpdate(
|
|
312
|
-
this._onModelEvent,
|
|
313
|
-
this.listeningContext || this
|
|
314
|
-
));
|
|
315
|
-
|
|
316
|
-
this._attachedModels = modelsToAttach;
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/**
|
|
320
|
-
* Removes all model event listeners from a component. This happens automatically
|
|
321
|
-
* on componentWillUnmount, but also before any listeners are manually attached.
|
|
322
|
-
*/
|
|
323
|
-
_unattachModelListeners() {
|
|
324
|
-
// Ensure that we clean up any dangling references when the component is destroyed.
|
|
325
|
-
(this._attachedModels || []).forEach((model) => model.offUpdate(
|
|
326
|
-
this.listeningContext || this
|
|
327
|
-
));
|
|
328
|
-
this._attachedModels = null;
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
render() {
|
|
332
|
-
var resources = this._generateResources().filter(withoutPrefetch),
|
|
333
|
-
loadingStates = getCriticalLoadingStates(this.state, resources);
|
|
334
|
-
|
|
335
|
-
return (
|
|
336
|
-
<ErrorBoundary>
|
|
337
|
-
<Component
|
|
338
|
-
{...(Component.prototype || {}).isReactComponent ? {
|
|
339
|
-
// allows for our listeners to call forceUpdate in this context, so that even
|
|
340
|
-
// PureComponents get updated
|
|
341
|
-
ref: (dataChild) => this.listeningContext = dataChild
|
|
342
|
-
} : {}}
|
|
343
|
-
|
|
344
|
-
// here we pass down our models
|
|
345
|
-
{...pick(
|
|
346
|
-
this.state,
|
|
347
|
-
...resources.map(([name, {modelKey}]) => getResourcePropertyName(name, modelKey))
|
|
348
|
-
)}
|
|
349
|
-
|
|
350
|
-
// here we include our model loading states, useful for noncritical resources
|
|
351
|
-
{...pick(this.state, ...resources.map(([name]) => getResourceState(name)))}
|
|
352
|
-
{...pick(this.state, ...resources.map(([name]) => getResourceStatus(name)))}
|
|
353
|
-
{...this.props}
|
|
354
|
-
|
|
355
|
-
// these props represent our critical resource loading states
|
|
356
|
-
hasErrored={hasErrored(loadingStates)}
|
|
357
|
-
hasInitiallyLoaded={this.state.hasInitiallyLoaded}
|
|
358
|
-
hasLoaded={hasLoaded(loadingStates)}
|
|
359
|
-
isLoading={isLoading(loadingStates)}
|
|
360
|
-
|
|
361
|
-
// helpers
|
|
362
|
-
refetch={this._refetch}
|
|
363
|
-
/>
|
|
364
|
-
</ErrorBoundary>
|
|
365
|
-
);
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
return DataCarrier;
|
|
370
|
-
};
|
|
371
|
-
|
|
372
|
-
/**
|
|
373
|
-
* Hook version of withResources, returning all of the same props otherwise
|
|
374
|
-
* passed down in the HOC, as well as a setResourceState() fn. See the comment
|
|
375
|
-
* above withResources for details on the getResources executor function, or
|
|
376
|
-
* check the README.
|
|
377
|
-
*/
|
|
378
58
|
export const useResources = (getResources, props) => {
|
|
379
59
|
var [_resourceState, setResourceState] = useState({}),
|
|
380
60
|
props = {...props, ..._resourceState},
|
|
@@ -629,6 +309,22 @@ export const useResources = (getResources, props) => {
|
|
|
629
309
|
};
|
|
630
310
|
};
|
|
631
311
|
|
|
312
|
+
/**
|
|
313
|
+
* HOC version of useResources, returning all of the same props otherwise returned by the hook. See
|
|
314
|
+
* the comment above useResources for details on the getResources executor function, or check the
|
|
315
|
+
* README.
|
|
316
|
+
*/
|
|
317
|
+
export const withResources = (getResources) => (Component) =>
|
|
318
|
+
function DataCarrier(props) {
|
|
319
|
+
var resources = useResources(getResources, props);
|
|
320
|
+
|
|
321
|
+
return (
|
|
322
|
+
<ErrorBoundary>
|
|
323
|
+
<Component {...props} {...resources} />
|
|
324
|
+
</ErrorBoundary>
|
|
325
|
+
);
|
|
326
|
+
};
|
|
327
|
+
|
|
632
328
|
/**
|
|
633
329
|
* Helper method to flatten the hash of resources returned by the `getResources`
|
|
634
330
|
* function into a single array of [name, config] entries. Resource values are
|
|
@@ -644,8 +340,7 @@ export const useResources = (getResources, props) => {
|
|
|
644
340
|
* @param {function} getResources - resources executor fn
|
|
645
341
|
* @param {object} props - current component props
|
|
646
342
|
* @return {[string, object][]} flattened [name, config] list of resources
|
|
647
|
-
* to be consumed by the
|
|
648
|
-
* assigned.
|
|
343
|
+
* to be consumed by the useResources with prefetch properties assigned.
|
|
649
344
|
*/
|
|
650
345
|
function generateResources(getResources, props) {
|
|
651
346
|
return Object.entries(getResources(ResourceKeys, props) || {})
|
|
@@ -667,7 +362,7 @@ function generateResources(getResources, props) {
|
|
|
667
362
|
|
|
668
363
|
/**
|
|
669
364
|
* @param {string} name - string name of the resource
|
|
670
|
-
* @return {string} name of the loading state property
|
|
365
|
+
* @return {string} name of the loading state property
|
|
671
366
|
*/
|
|
672
367
|
function getResourceState(name) {
|
|
673
368
|
return `${name}LoadingState`;
|
|
@@ -675,7 +370,7 @@ function getResourceState(name) {
|
|
|
675
370
|
|
|
676
371
|
/**
|
|
677
372
|
* @param {string} name - string name of the resource
|
|
678
|
-
* @return {string} name of the status property
|
|
373
|
+
* @return {string} name of the status property
|
|
679
374
|
*/
|
|
680
375
|
function getResourceStatus(name) {
|
|
681
376
|
return `${name}Status`;
|
|
@@ -698,7 +393,7 @@ function getResourcePropertyName(baseName, modelKey) {
|
|
|
698
393
|
}
|
|
699
394
|
|
|
700
395
|
/**
|
|
701
|
-
* When a resource is not found in the ModelCache,
|
|
396
|
+
* When a resource is not found in the ModelCache, resourcerer returns a
|
|
702
397
|
* default empty resource so that clients can assume the model is defined
|
|
703
398
|
* without needing to be defensive. This method freezes an empty instance of
|
|
704
399
|
* the model associated with the modelKey and returns it.
|
package/package.json
CHANGED
package/test/prefetch.test.js
CHANGED
|
@@ -6,7 +6,7 @@ import prefetch from '../lib/prefetch';
|
|
|
6
6
|
import ReactDOM from 'react-dom';
|
|
7
7
|
|
|
8
8
|
const renderNode = document.createElement('div');
|
|
9
|
-
const getResources = (
|
|
9
|
+
const getResources = ({DECISIONS, USER}, props) => ({
|
|
10
10
|
[USER]: {
|
|
11
11
|
data: {home: props.home, source: props.source},
|
|
12
12
|
options: {userId: props.userId}
|
package/test/sync.test.js
CHANGED
package/test/test-utils.js
CHANGED
|
@@ -29,83 +29,3 @@ export function waitsFor(condition, time=3000, name='something to happen') {
|
|
|
29
29
|
}, 0);
|
|
30
30
|
});
|
|
31
31
|
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Returns reference the wrapped DataCarrier instance, which is in charge of
|
|
35
|
-
* keeping loading states as state and passing down our models from the model
|
|
36
|
-
* cache into the data child.
|
|
37
|
-
*
|
|
38
|
-
* @param {object} tree - the top node returned from a withResources declaration
|
|
39
|
-
* @return {object} the wrapped DataCarrier instance
|
|
40
|
-
*/
|
|
41
|
-
export function findDataCarrier(tree) {
|
|
42
|
-
wrapperCheck(tree);
|
|
43
|
-
|
|
44
|
-
return findChildAtDepth(tree, 1);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Returns reference the wrapped DataChild instance, which is the user-defined
|
|
49
|
-
* component that gets the @withResources decorator attached to it.
|
|
50
|
-
*
|
|
51
|
-
* @param {object} tree - the top node returned from a withResources declaration
|
|
52
|
-
* @return {object} the wrapped DataChild instance
|
|
53
|
-
*/
|
|
54
|
-
export function findDataChild(tree) {
|
|
55
|
-
wrapperCheck(tree);
|
|
56
|
-
|
|
57
|
-
return findChildAtDepth(tree, 3);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/**
|
|
61
|
-
* Return an object with reference all wrapped children returned within a
|
|
62
|
-
* withResources declaration instance.
|
|
63
|
-
*
|
|
64
|
-
* @param {object} tree - the top node returned from a withResources declaration
|
|
65
|
-
* @return {object} an object containing references to the parent resources
|
|
66
|
-
* component, the data carrier, data child, and even the error boundary
|
|
67
|
-
* component instances.
|
|
68
|
-
*/
|
|
69
|
-
export function getRenderedResourceComponents(tree) {
|
|
70
|
-
wrapperCheck(tree);
|
|
71
|
-
|
|
72
|
-
return {
|
|
73
|
-
resources: tree,
|
|
74
|
-
dataCarrier: findDataCarrier(tree),
|
|
75
|
-
dataChild: findDataChild(tree),
|
|
76
|
-
errorBoundary: findChildAtDepth(tree, 2)
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* In order for the wrapped-component convenience methods to work, the argument
|
|
82
|
-
* must be an instance of ResourceStateWrapper returned from a `withResources`
|
|
83
|
-
* declaration. This check throws an error if that is not the case.
|
|
84
|
-
*
|
|
85
|
-
* @param {object} tree - the top node for which to verify its type
|
|
86
|
-
*/
|
|
87
|
-
function wrapperCheck(tree) {
|
|
88
|
-
if (Object.getPrototypeOf(tree).constructor.name !== 'ResourceStateWrapper') {
|
|
89
|
-
throw new Error('Component must be of type returned by withResources function');
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* Core to our wrapped-component convenience methods, we simply walk down the
|
|
95
|
-
* React tree a specified depth, which we know to always be true for our
|
|
96
|
-
* wrapped components. This is all-the-easier because there are no siblings to
|
|
97
|
-
* crawl.
|
|
98
|
-
*
|
|
99
|
-
* @param {object} node - entry in the React render tree
|
|
100
|
-
* @param {number} depth - number of entries to crawl to get the child of interest
|
|
101
|
-
* @return {object} rendered instance of wrapped component
|
|
102
|
-
*/
|
|
103
|
-
function findChildAtDepth(node, depth=0) {
|
|
104
|
-
var i = 0;
|
|
105
|
-
|
|
106
|
-
while (i++ < depth) {
|
|
107
|
-
node = node.child || node._reactInternalFiber.child;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
return node.stateNode;
|
|
111
|
-
}
|