resourcerer 1.0.0-beta-5 → 1.0.0
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 +28 -30
- package/lib/request.js +11 -4
- package/lib/resourcerer.js +3 -1
- package/package.json +1 -1
- package/test/request.test.js +51 -8
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,
|
|
@@ -134,7 +133,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
|
|
|
134
133
|
1. [params](#params)
|
|
135
134
|
1. [options](#options)
|
|
136
135
|
1. [noncritical](#noncritical)
|
|
137
|
-
1. [
|
|
136
|
+
1. [force](#force)
|
|
138
137
|
1. [Custom Resource Names](#custom-resource-names)
|
|
139
138
|
1. [prefetches](#prefetches)
|
|
140
139
|
1. [data](#data)
|
|
@@ -178,7 +177,7 @@ module: {
|
|
|
178
177
|
|
|
179
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.
|
|
180
179
|
|
|
181
|
-
1. **Executor Function**. The executor function is a function that both the hook and HOC accept that declaratively describes which resources to request and with what config options. It accepts `ResourceKeys` and `props` as arguments and may look like, as we'll explore in an example later:
|
|
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:
|
|
182
181
|
|
|
183
182
|
```js
|
|
184
183
|
const getResources = ({USER}, props) => ({[USER]: {options: {userId: props.id}}});
|
|
@@ -203,7 +202,7 @@ module: {
|
|
|
203
202
|
};
|
|
204
203
|
```
|
|
205
204
|
|
|
206
|
-
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).
|
|
207
206
|
|
|
208
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.
|
|
209
208
|
|
|
@@ -218,7 +217,7 @@ Okay, back to the initial example. Let's take a look at our `useResources` usage
|
|
|
218
217
|
const getResources = (ResourceKeys, props) => ({[ResourceKeys.TODOS]: {}});
|
|
219
218
|
|
|
220
219
|
export default function MyComponent(props) {
|
|
221
|
-
|
|
220
|
+
const resources = useResources(getResources, props);
|
|
222
221
|
|
|
223
222
|
// ...
|
|
224
223
|
}
|
|
@@ -264,7 +263,7 @@ const getResources = ({TODOS, USERS}, props) => ({
|
|
|
264
263
|
});
|
|
265
264
|
|
|
266
265
|
function MyClassWithTodosAndAUsers(props) {
|
|
267
|
-
|
|
266
|
+
const resources = useResources(getResources, props);
|
|
268
267
|
}
|
|
269
268
|
```
|
|
270
269
|
|
|
@@ -284,7 +283,7 @@ Here’s how might use that to our advantage in `MyClassWithTodosAndAUsers` :
|
|
|
284
283
|
import {haveAllLoaded} from 'resourcerer';
|
|
285
284
|
|
|
286
285
|
function MyClassWithTodosAndAUsers(props) {
|
|
287
|
-
|
|
286
|
+
const {
|
|
288
287
|
isLoading,
|
|
289
288
|
hasErrored,
|
|
290
289
|
hasLoaded,
|
|
@@ -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
|
}
|
|
@@ -492,12 +491,12 @@ As alluded to in the [Other Props](#other-props-returned-from-the-hookpassed-fro
|
|
|
492
491
|
|
|
493
492
|
|
|
494
493
|
|
|
495
|
-
###
|
|
494
|
+
### force
|
|
496
495
|
|
|
497
|
-
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.
|
|
498
497
|
|
|
499
498
|
```js
|
|
500
|
-
@withResources((ResourceKeys, props) => ({[ResourceKeys.LATEST_STATS]: {
|
|
499
|
+
@withResources((ResourceKeys, props) => ({[ResourceKeys.LATEST_STATS]: {force: true}}))
|
|
501
500
|
class MyComponentWithLatestStats extends React.Component {}
|
|
502
501
|
```
|
|
503
502
|
|
|
@@ -509,7 +508,7 @@ Passing a `modelKey: <ResourceKeys>` option allows you to pass a custom name as
|
|
|
509
508
|
const getResources = (ResourceKeys, props) => ({myRadTodos: {modelKey: ResourceKeys.TODOS});
|
|
510
509
|
|
|
511
510
|
export default function MyComponentWithTodos {
|
|
512
|
-
|
|
511
|
+
const {
|
|
513
512
|
myRadTodosCollection,
|
|
514
513
|
myRadTodosLoadingState,
|
|
515
514
|
myRadTodosStatus,
|
|
@@ -566,7 +565,7 @@ Pass in a data hash to initialize a Model instance with data before initially fe
|
|
|
566
565
|
getResources = ({CUSTOMER}) => ({[CUSTOMER]: {data: {id: props.customerId}}});
|
|
567
566
|
|
|
568
567
|
function MyCustomerComponent(props) {
|
|
569
|
-
|
|
568
|
+
const {customerModel} = useResources(getResources, props);
|
|
570
569
|
|
|
571
570
|
// now you can reference the id directly on the model
|
|
572
571
|
console.log(customerModel.get('id')); // or the id shorthand, customerModel.id
|
|
@@ -595,10 +594,10 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
|
|
|
595
594
|
|
|
596
595
|
```js
|
|
597
596
|
function MyComponent(props) {
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
597
|
+
const {myModel} = useResources(getResources, props),
|
|
598
|
+
onSave = () => myModel.save({foo: 'bar'})
|
|
599
|
+
.then([model]) => // ...)
|
|
600
|
+
.catch(() => alert('request failed'));
|
|
602
601
|
|
|
603
602
|
return <button onClick={onSave}>Persist model</button>;
|
|
604
603
|
}
|
|
@@ -618,8 +617,8 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
|
|
|
618
617
|
|
|
619
618
|
```js
|
|
620
619
|
function TodoDetails(props) {
|
|
621
|
-
|
|
622
|
-
|
|
620
|
+
const {hasLoaded, todosCollection} = useResources(getResources, props),
|
|
621
|
+
todoModel = todosCollection.get(props.id),
|
|
623
622
|
|
|
624
623
|
onSaveTodo = {
|
|
625
624
|
// set some loading state...
|
|
@@ -656,8 +655,7 @@ Each one of these methods exhibit the following behaviors:
|
|
|
656
655
|
**Note:**
|
|
657
656
|
1. All calls resolve an array, which is a tuple of [model, response]. All reject with just the response.
|
|
658
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.
|
|
659
|
-
|
|
660
|
-
|
|
658
|
+
|
|
661
659
|
## Serial Requests
|
|
662
660
|
|
|
663
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.
|
|
@@ -704,7 +702,7 @@ const getResources = ({QUEUE_ITEM, USER}, props) => ({
|
|
|
704
702
|
|
|
705
703
|
export default function QueueItemPage(props) {
|
|
706
704
|
// activeState and userId are internal state within `useResources` and returned
|
|
707
|
-
|
|
705
|
+
const {
|
|
708
706
|
activeState,
|
|
709
707
|
userId,
|
|
710
708
|
userModel,
|
|
@@ -728,7 +726,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
|
|
|
728
726
|
|
|
729
727
|
```js
|
|
730
728
|
function MyComponent({start_time, ...props}) {
|
|
731
|
-
|
|
729
|
+
const {todosCollection} = useResources(({TODOS}, _props) => ({[TODOS]: {params: {start_time}}}), props);
|
|
732
730
|
|
|
733
731
|
// ...
|
|
734
732
|
```
|
|
@@ -737,7 +735,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
|
|
|
737
735
|
|
|
738
736
|
```js
|
|
739
737
|
function MyComponent(props) {
|
|
740
|
-
|
|
738
|
+
const {todosCollection} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
|
|
741
739
|
|
|
742
740
|
// ...
|
|
743
741
|
```
|
|
@@ -748,7 +746,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
|
|
|
748
746
|
const getResources = ({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}});
|
|
749
747
|
|
|
750
748
|
function MyComponent(props) {
|
|
751
|
-
|
|
749
|
+
const {todosCollection} = useResources(getResources, props);
|
|
752
750
|
|
|
753
751
|
// ...
|
|
754
752
|
```
|
|
@@ -861,7 +859,7 @@ It takes a function that is passed `ResourceKeys` and should return a list of `R
|
|
|
861
859
|
|
|
862
860
|
```js
|
|
863
861
|
function MyComponent(props) {
|
|
864
|
-
|
|
862
|
+
const {todosCollection, refetch} = useResources(({TODOS}, {start_time}) => ({[TODOS]: {params: {start_time}}}), props);
|
|
865
863
|
|
|
866
864
|
// ...
|
|
867
865
|
|
|
@@ -1012,12 +1010,12 @@ ResourcesConfig.set(configObj);
|
|
|
1012
1010
|
|
|
1013
1011
|
// component1
|
|
1014
1012
|
function MyComponent({category, ...props}) {
|
|
1015
|
-
|
|
1013
|
+
const {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
|
|
1016
1014
|
}
|
|
1017
1015
|
|
|
1018
1016
|
// component2--identical to the first
|
|
1019
1017
|
function MyComponent({category, ...props}) {
|
|
1020
|
-
|
|
1018
|
+
const {todosCollection} = useResources(({TODOS}) => ({[TODOS]: {options: {category}}));
|
|
1021
1019
|
}
|
|
1022
1020
|
```
|
|
1023
1021
|
|
package/lib/request.js
CHANGED
|
@@ -38,7 +38,7 @@ export const existsInCache = (key) => !!ModelCache.get(key);
|
|
|
38
38
|
* * data {object|object[]} - attributes or models to pass a Model or Collection instance, resp.
|
|
39
39
|
* * params {object} - query params to pass into the fetch method
|
|
40
40
|
* * fetch {boolean} - whether fetch the model after creation
|
|
41
|
-
* *
|
|
41
|
+
* * force {boolean} - force the fetch to be made if the model is already cached
|
|
42
42
|
* * method {string} - request type (GET|POST|PUT|DELETE)
|
|
43
43
|
* * options {object} - options to pass to the Model constructor
|
|
44
44
|
* * prefetch {boolean} - whether the request should be treated as a prefetched resource
|
|
@@ -54,20 +54,23 @@ export default (key, Model, options={}) => {
|
|
|
54
54
|
data: Model && Model.prototype instanceof Collection ? [] : {},
|
|
55
55
|
params: {},
|
|
56
56
|
options: {},
|
|
57
|
-
fetch:
|
|
58
|
-
|
|
57
|
+
fetch: !options.lazy,
|
|
58
|
+
force: false,
|
|
59
|
+
lazy: false,
|
|
59
60
|
method: 'GET',
|
|
60
61
|
...options
|
|
61
62
|
};
|
|
62
63
|
|
|
63
64
|
if (!loadingCache[key]) {
|
|
64
65
|
_promise = new Promise((resolve, reject) => {
|
|
65
|
-
if (!model || options.
|
|
66
|
+
if (!model || model.lazy || options.force) {
|
|
66
67
|
model = model || new Model(options.data, options.options);
|
|
67
68
|
|
|
68
69
|
if (options.fetch) {
|
|
69
70
|
addToLoadingCache = true;
|
|
70
71
|
|
|
72
|
+
delete model.lazy;
|
|
73
|
+
|
|
71
74
|
model.fetch({params: options.params}).then(
|
|
72
75
|
([newModel, response]) => {
|
|
73
76
|
delete loadingCache[key];
|
|
@@ -80,6 +83,10 @@ export default (key, Model, options={}) => {
|
|
|
80
83
|
}
|
|
81
84
|
);
|
|
82
85
|
} else {
|
|
86
|
+
// lazy means resolove but don't fetch yet; it will get updates from other components
|
|
87
|
+
// we only want to do this if a model is not yet in the cache
|
|
88
|
+
options.lazy && !ModelCache.get(key) ? model.lazy = true : null;
|
|
89
|
+
|
|
83
90
|
ModelCache.put(key, model, options.component);
|
|
84
91
|
resolve([model]);
|
|
85
92
|
}
|
package/lib/resourcerer.js
CHANGED
|
@@ -44,6 +44,8 @@ const SPREAD_PROVIDES_CHAR = '_';
|
|
|
44
44
|
* a value to be set for the prop. If the key is equal to
|
|
45
45
|
* SPREAD_PROVIDES_CHAR, then the return value of the transform function
|
|
46
46
|
* is spread for dynamically-provided props.
|
|
47
|
+
* * force {boolean} - force a fetch request regardless of whether the model
|
|
48
|
+
* is already in the cache
|
|
47
49
|
* * prefetch {object} - an individual map of expected future props to fetch
|
|
48
50
|
* a new resource and store it in the cache. it will not, however, get
|
|
49
51
|
* passed down to the child (no loading states, either)
|
|
@@ -817,7 +819,7 @@ function fetchResources(resources, props, {
|
|
|
817
819
|
fetch: !UnfetchedResources.has(modelKey),
|
|
818
820
|
params,
|
|
819
821
|
component,
|
|
820
|
-
|
|
822
|
+
force: refetch,
|
|
821
823
|
...rest
|
|
822
824
|
}).then(
|
|
823
825
|
// success callback, where we track request time and add any dependent props or models
|
package/package.json
CHANGED
package/test/request.test.js
CHANGED
|
@@ -126,10 +126,7 @@ describe('Request', () => {
|
|
|
126
126
|
|
|
127
127
|
describe('if the \'fetch\' option is false', () => {
|
|
128
128
|
it('calls the resolve immediately', async() => {
|
|
129
|
-
var model;
|
|
130
|
-
|
|
131
|
-
request('nofetch', Model, {component, fetch: false})
|
|
132
|
-
.then(([_model]) => model = _model);
|
|
129
|
+
var [model] = await request('nofetch', Model, {component, fetch: false});
|
|
133
130
|
|
|
134
131
|
await waitsFor(() => model instanceof Model);
|
|
135
132
|
|
|
@@ -140,8 +137,7 @@ describe('Request', () => {
|
|
|
140
137
|
var model;
|
|
141
138
|
|
|
142
139
|
expect(ModelCache.get('nofetch')).not.toBeDefined();
|
|
143
|
-
request('nofetch', Model, {component, fetch: false})
|
|
144
|
-
.then(([_model]) => model = _model);
|
|
140
|
+
[model] = await request('nofetch', Model, {component, fetch: false});
|
|
145
141
|
|
|
146
142
|
await waitsFor(() => model instanceof Model);
|
|
147
143
|
|
|
@@ -263,7 +259,7 @@ describe('Request', () => {
|
|
|
263
259
|
});
|
|
264
260
|
});
|
|
265
261
|
|
|
266
|
-
describe('requested with {
|
|
262
|
+
describe('requested with {force: true}', () => {
|
|
267
263
|
var startModel,
|
|
268
264
|
finalModel;
|
|
269
265
|
|
|
@@ -273,7 +269,7 @@ describe('Request', () => {
|
|
|
273
269
|
startModel = await request('bar', Model, {component});
|
|
274
270
|
Model.prototype.fetch.mockClear();
|
|
275
271
|
|
|
276
|
-
finalModel = await request('bar', Model, {component,
|
|
272
|
+
finalModel = await request('bar', Model, {component, force: true});
|
|
277
273
|
});
|
|
278
274
|
|
|
279
275
|
afterEach(() => {
|
|
@@ -288,6 +284,53 @@ describe('Request', () => {
|
|
|
288
284
|
expect(startModel).toEqual(finalModel);
|
|
289
285
|
});
|
|
290
286
|
});
|
|
287
|
+
|
|
288
|
+
describe('with the \'lazy\' option', () => {
|
|
289
|
+
it('returns a new model without fetching', async() => {
|
|
290
|
+
await request('lazy', Model, {component, lazy: true});
|
|
291
|
+
|
|
292
|
+
expect(Model.prototype.fetch).not.toHaveBeenCalled();
|
|
293
|
+
expect(ModelCache.put).toHaveBeenCalled();
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
it('returns an existing model without fetching', async() => {
|
|
297
|
+
var existingModel = new Model(),
|
|
298
|
+
model;
|
|
299
|
+
|
|
300
|
+
ModelCache.put('lazy', existingModel, component);
|
|
301
|
+
[model] = await request('lazy', Model, {component, lazy: true});
|
|
302
|
+
|
|
303
|
+
expect(Model.prototype.fetch).not.toHaveBeenCalled();
|
|
304
|
+
expect(ModelCache.put).toHaveBeenCalled();
|
|
305
|
+
expect(existingModel).toEqual(model);
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
it('fetches when another component requests the same model without lazy option', async() => {
|
|
309
|
+
var [model] = await request('lazy', Model, {component, lazy: true});
|
|
310
|
+
|
|
311
|
+
expect(model.lazy).toBe(true);
|
|
312
|
+
expect(Model.prototype.fetch).not.toHaveBeenCalled();
|
|
313
|
+
|
|
314
|
+
[model] = await request('lazy', Model, {component});
|
|
315
|
+
expect(model.lazy).not.toBeDefined();
|
|
316
|
+
expect(Model.prototype.fetch).toHaveBeenCalled();
|
|
317
|
+
|
|
318
|
+
Model.prototype.fetch.mockClear();
|
|
319
|
+
|
|
320
|
+
// now if we ask for lazy again, followed by another non-lazy, it's already in the cache and
|
|
321
|
+
// we will not re-fetch
|
|
322
|
+
[model] = await request('lazy', Model, {component, lazy: true});
|
|
323
|
+
expect(model.lazy).not.toBeDefined();
|
|
324
|
+
[model] = await request('lazy', Model, {component});
|
|
325
|
+
expect(model.lazy).not.toBeDefined();
|
|
326
|
+
expect(Model.prototype.fetch).not.toHaveBeenCalled();
|
|
327
|
+
|
|
328
|
+
// now with two lazy requests (ie from different components), it still does not get fetched
|
|
329
|
+
await request('lazy', Model, {component, lazy: true});
|
|
330
|
+
await request('lazy', Model, {component: {}, lazy: true});
|
|
331
|
+
expect(Model.prototype.fetch).not.toHaveBeenCalled();
|
|
332
|
+
});
|
|
333
|
+
});
|
|
291
334
|
});
|
|
292
335
|
|
|
293
336
|
describe('when using getFromCache', () => {
|