resourcerer 1.0.13 → 1.1.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 +62 -16
- package/docs/advanced_topics.md +299 -0
- package/docs/collection.md +246 -0
- package/docs/model.md +203 -0
- package/docs/testing_components.md +58 -0
- package/docs/typescript.md +94 -0
- package/index.d.ts +245 -0
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -15,6 +15,7 @@ Additional features include:
|
|
|
15
15
|
* fully declarative (no more writing any imperative Fetch API calls)
|
|
16
16
|
* first-class loading and error state support
|
|
17
17
|
* smart client-side caching
|
|
18
|
+
* lazy fetching
|
|
18
19
|
* refetching
|
|
19
20
|
* updating a component when a resource updates
|
|
20
21
|
* zero dependencies
|
|
@@ -137,11 +138,13 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
|
|
|
137
138
|
1. [Custom Resource Names](#custom-resource-names)
|
|
138
139
|
1. [prefetches](#prefetches)
|
|
139
140
|
1. [data](#data)
|
|
141
|
+
1. [lazy](#lazy)
|
|
140
142
|
1. [dependsOn](#dependson)
|
|
141
143
|
1. [provides](#provides)
|
|
142
144
|
1. [Data mutations](#data-mutations)
|
|
143
145
|
1. [Serial Requests](#serial-requests)
|
|
144
146
|
3. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
|
|
147
|
+
4. [Using resourcerer with TypeScript](docs/typescript.md)
|
|
145
148
|
4. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
|
|
146
149
|
5. [Declarative Cache Keys](#declarative-cache-keys)
|
|
147
150
|
6. [Prefetch on Hover](#prefetch-on-hover)
|
|
@@ -157,7 +160,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
|
|
|
157
160
|
|
|
158
161
|
`resourcerer` requires on React >= 16.8 but has no external dependencies.
|
|
159
162
|
|
|
160
|
-
Note that Resourcerer uses
|
|
163
|
+
Note that Resourcerer uses ESNext in its source and does no transpiling—including import/export (Local babel configuration is for testing, only).
|
|
161
164
|
This means that if you're not babelifying your `node_modules` folder, you'll need to make an exception for this package, ie:
|
|
162
165
|
|
|
163
166
|
```js
|
|
@@ -241,7 +244,7 @@ ModelMap.add({TODOS: TodosCollection});
|
|
|
241
244
|
|
|
242
245
|
(We can also pass custom prefixes for our prop names in a component, but [we'll get to that later](#custom-resource-names).)
|
|
243
246
|
|
|
244
|
-
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 `{
|
|
247
|
+
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 `{[key: ResourceKeys]: 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.
|
|
245
248
|
|
|
246
249
|
|
|
247
250
|
## Other Props Returned from the Hook/Passed from the HOC (Loading States)
|
|
@@ -576,6 +579,49 @@ You can also use `data` to take advantage of [re-caching](/docs/advanced_topics.
|
|
|
576
579
|
|
|
577
580
|
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
581
|
|
|
582
|
+
### lazy
|
|
583
|
+
|
|
584
|
+
Lazy fetching is one of resourcerer's most powerful features, allowing you to get a reference to a model without actually fetching it. If the model is ultimately fetched elsewhere on the page, the component that lazily fetched it will still listen for updates.
|
|
585
|
+
|
|
586
|
+
A great example of when this would be useful is for search results. Search results are read-only, but if you modify the entity of a result somewhere else in the page, you'd like to see it reflected in your search results. Yet you don't want to fetch the entity details for every search result and spam your API. Enter lazy loading:
|
|
587
|
+
|
|
588
|
+
```jsx
|
|
589
|
+
// todo_search.jsx
|
|
590
|
+
getResources = ({TODOS_SEARCH}) => ({[TODOS_SEARCH]: {params: someSearchParams}});
|
|
591
|
+
|
|
592
|
+
function TodoSearch(props) {
|
|
593
|
+
const {todoSearchModel} = useResources(getResources, props);
|
|
594
|
+
|
|
595
|
+
return (
|
|
596
|
+
<Table>
|
|
597
|
+
<thead>
|
|
598
|
+
<TableHeader>Name</TableHeader>
|
|
599
|
+
<TableHeader>Last Updated</TableHeader>
|
|
600
|
+
</thead>
|
|
601
|
+
<tbody>
|
|
602
|
+
{todoSearchModel.get('results').map((todo) => <TodoSearchItem {...todo} />)}
|
|
603
|
+
</tbody>
|
|
604
|
+
</Table>
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// todo_search_item.jsx
|
|
609
|
+
// the todoModel is never actually fetched here, it's only listened on, allowing any changes made elsewhere in the page to be reflected here.
|
|
610
|
+
getResources = ({TODO}) => ({[TODO]: {id: props.id, lazy: true}});
|
|
611
|
+
|
|
612
|
+
function TodoSearchItem(props) {
|
|
613
|
+
const {todoModel} = useResources(getResources, props);
|
|
614
|
+
|
|
615
|
+
return (
|
|
616
|
+
<tr>
|
|
617
|
+
<td>{todoModel.get('name') || props.name}</td>
|
|
618
|
+
<td>{todoModel.get('updated_at') || props.updated_at}</td>
|
|
619
|
+
</tr>
|
|
620
|
+
);
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
If the todo model has been fetched already, we'll read straight from that. And if it gets updated, this component, via resourcerer, is listening for updates and will re-render to keep our entire UI in sync. Otherwise, we'll just fall back to our read-only search results. WIN!
|
|
624
|
+
|
|
579
625
|
### dependsOn
|
|
580
626
|
|
|
581
627
|
See the section on [serial requests](#serial-requests).
|
|
@@ -620,20 +666,20 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
|
|
|
620
666
|
const {hasLoaded, todosCollection} = useResources(getResources, props),
|
|
621
667
|
todoModel = todosCollection.get(props.id),
|
|
622
668
|
|
|
623
|
-
|
|
624
|
-
|
|
669
|
+
onSaveTodo = {
|
|
670
|
+
// set some loading state...
|
|
625
671
|
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
672
|
+
if (!props.id) {
|
|
673
|
+
// create new todo!
|
|
674
|
+
return todosCollection.create(attrs)
|
|
675
|
+
.then(([model]) => // ...)
|
|
676
|
+
.catch(() => alert('create failed'));
|
|
677
|
+
.then(() => // remove loading state);
|
|
678
|
+
}
|
|
633
679
|
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
680
|
+
// update existing
|
|
681
|
+
todoModel.save(attrs).then(([model]) => ...).catch(() => alert('update failed'));
|
|
682
|
+
};
|
|
637
683
|
|
|
638
684
|
if (hasLoaded && props.id && !todoModel) {
|
|
639
685
|
return <p>Todo not found.</p>;
|
|
@@ -678,7 +724,7 @@ function getUserIdFromItem(queueItemModel) {
|
|
|
678
724
|
}
|
|
679
725
|
```
|
|
680
726
|
|
|
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
|
|
727
|
+
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 `[key: string]: (model: Model | Collection) => any`, 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
728
|
|
|
683
729
|
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
730
|
|
|
@@ -755,7 +801,7 @@ The hook and HOC largely operate interchangeably, but do note a couple critical
|
|
|
755
801
|
|
|
756
802
|
`resourcerer` handles resource storage and caching, so that when multiple components request the same resource with the same parameters or the same body, they receive the same model in response. If multiple components request a resource still in-flight, only a single request is made, and each component awaits the return of the same resource. Fetched resources are stored in the `ModelCache`. Under most circumstances, you won’t need to interact with directly; but it’s still worth knowing a little bit about what it does.
|
|
757
803
|
|
|
758
|
-
The `ModelCache` is a simple module that contains a couple of Maps—one that is the actual cache `{cacheKey
|
|
804
|
+
The `ModelCache` is a simple module that contains a couple of Maps—one that is the actual cache `{[cacheKey: string]: Model | Collection}`, and one that is a component manifest, keeping track of all component instances that are using a given resource (unique by cache key). When a component unmounts, `resourcerer` will unregister the component instance from the component manifest; if a resource no longer has any component instances attached, it gets scheduled for cache removal. The timeout period for cache removal is two minutes by default (but can be changed, see [Configuring resourcerer](#configuring-resourcerer), or [overridden on a model-class basis](/docs/model.md#static-cachetimeout)), to allow navigating back and forth between pages without requiring a refetch of all resources. After the timeout, if no other new component instances have requested the resource, it’s removed from the `ModelCache`. Any further requests for that resource then go back through the network.
|
|
759
805
|
|
|
760
806
|
Again, it’s unlikely that you’ll use `ModelCache` directly while using `resourcerer`, but it’s helpful to know a bit about what’s going on behind-the-scenes.
|
|
761
807
|
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
# Contents
|
|
2
|
+
|
|
3
|
+
1. [Thoughts on the PENDING Resource](#thoughts-on-the-pending-resource)
|
|
4
|
+
1. [Implicit dependent resources](#implicit-dependent-resources)
|
|
5
|
+
1. [Unfetched Resources](#unfetched-resources)
|
|
6
|
+
1. [Loading Overlays](#loading-overlays)
|
|
7
|
+
1. [isOrWillBeLoading](#isorwillbeloading)
|
|
8
|
+
1. [Recaching newly-saved models](#recaching-newly-saved-models)
|
|
9
|
+
|
|
10
|
+
## Thoughts on the PENDING Resource
|
|
11
|
+
|
|
12
|
+
Using `dependsOn` in simple cases like the one highlighted in the [README](https://github.com/noahgrant/resourcerer/blob/master/README.md) is pretty straightforward and very powerful. But `PENDING` resources bring additional complexities to your resource logic, some of which are enumerated here:
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
1. `PENDING` critical resources don’t contribute to `isLoading`/`hasErrored` states, but will keep your component from reaching a `hasLoaded` state. Semantically, this makes sense, because `hasLoaded` should only be true when all critical resources have loaded, regardless of when a resource’s request is made.
|
|
17
|
+
|
|
18
|
+
1. When a `PENDING` resource request is not in flight, its model prop will still be the empty model instance whose properties are frozen (as happens when the resource is in the other three possible loading states). This is to more predictably handle our resources in our components. We don’t need to be defensive with syntax like:
|
|
19
|
+
|
|
20
|
+
```js
|
|
21
|
+
todosCollection && todosCollection.toJSON(); // unnecessary
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Furthermore, if you've defined additional instance methods on your model, they will be present without being defensive:
|
|
25
|
+
|
|
26
|
+
```js
|
|
27
|
+
todosCollection.myInstanceMethod(); // guaranteed not to error regardless of loading state
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
1. When a previously-`PENDING` but currently `LOADED` resource has its dependent prop removed, it goes back to a `PENDING` state (recall that if the dependent prop is changed, it gets put back into a `LOADING` state while the new resource is fetched). This puts us in an interesting state:
|
|
31
|
+
|
|
32
|
+
1. `hasInitiallyLoaded` will remain true, as expected. But the `PENDING` resource’s prop—assuming the resource’s `cacheFields` list includes the dependent prop—will now return to the empty model/collection, so any child component that may remain in place after `hasInitiallyLoaded` may need to keep that in mind (if `shouldComponentUpdate` returns false when the new resource fetches, then this shouldn’t matter—see the next point).
|
|
33
|
+
|
|
34
|
+
2. Recall that we can provide the dependent prop in one of two ways:
|
|
35
|
+
1. We can include it in another resource’s `provides` property, in which case the dependent prop gets set as state within resourcerer.
|
|
36
|
+
1. We can also set state in our client component and pass it to the executor function, but that requires an extra render cycle.
|
|
37
|
+
1. We can modify the url in the component’s `componentDidUpdate`/`useEffect` (either url path or query parameter), which will filter the prop down.
|
|
38
|
+
|
|
39
|
+
When we provide using method (a), the dependent prop can be changed but not removed. When we provide using method (b), the dependent prop can be changed or removed.
|
|
40
|
+
|
|
41
|
+
So if we use method (b) and remove the dependent prop, we enter a state where `isLoading`, `hasLoaded`, and `hasErrored` are all false. And since we have to wait for a `componentDidUpdate`/`useEffect` to re-update the url with the dependent prop, a lifecycle passes with this state, and there’s really nothing we can do about it.
|
|
42
|
+
|
|
43
|
+
And again—`hasInitiallyLoaded` is still true and the model prop is empty, which can cause layout issues if you use, for example, an overlaid loader over a previously-rendered component. For this reason, if using classes/`withResources`, such a previously-rendered component should use `nextProps.hasLoaded` instead of `!nextProps.isLoading` in its `shouldComponentUpdate`:
|
|
44
|
+
|
|
45
|
+
```js
|
|
46
|
+
// overlay-wrapped component, where a loader will show over previously-rendered children,
|
|
47
|
+
// which we want to then not update. but this component is also a child of a `withResources`
|
|
48
|
+
// component that has a dependent resource
|
|
49
|
+
shouldComponentUpdate(nextProps) {
|
|
50
|
+
// using `return !nextProps.isLoading;` would update the component in the above
|
|
51
|
+
// scenario, even though `nextProps.myDependentModel` would be empty
|
|
52
|
+
return nextProps.hasLoaded;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// this assumes that the parent is handling the `hasErrored` state. if it is not, then
|
|
56
|
+
// you may need to instead use:
|
|
57
|
+
shouldComponentUpdate(nextProps) {
|
|
58
|
+
return !(nextProps.isLoading || areAnyPending(nextProps.myDependentLoadingState));
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
As an example of how we might be able to remove a dependent prop, consider someone navigating to a `/todos` url that auto-navigates to the first todo item and displays its details. The `todoItem` details resource depends on a `todoId` prop, which it gets in a `componentWillReceiveProps` via changing the url once the `todos` resource loads. So now we’re at `/todos/todo1234`. But if the user clicks the back button, we’ll be back at `/todos` with a cached `todos` resource and `PENDING` `todoItem` resource, and all three loading states set to `false`. (Yes, this is a bit contrived because you should actually replace the history entry in this case, but hopefully it helps to illuminate the issue.)
|
|
63
|
+
|
|
64
|
+
3. In the case that the model's `cacheFields` does not include the dependent prop (ie, the prop is used solely for triggering the resource request and doesn't factor into the request data), the model will still exist in the cache when the dependent prop is removed. In this case, the loading state is still returned to PENDING, but the existing model will also be present in the return value.
|
|
65
|
+
|
|
66
|
+
## Implicit dependent resources
|
|
67
|
+
|
|
68
|
+
Another way to effectively have a dependent resource is to use a conditional in your `getResources` method:
|
|
69
|
+
|
|
70
|
+
```js
|
|
71
|
+
const getResources = (ResourceKeys, props) => ({
|
|
72
|
+
[ResourceKeys.TODOS]: {},
|
|
73
|
+
...(props.todoId ? {[ResourceKeys.TODO_ITEM]: {data: {id: props.todoId}} : {})
|
|
74
|
+
});
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
In general, using `dependsOn` is much more preferable, both in terms of semantics and functionality. The key difference here is that the dependent resource does not get put into a `PENDING` state, and `hasLoaded` depends on an unpredictable number of resources—for example, in the above scenario, what happens if `props.todoId` never arrives? Using `dependsOn`, `hasLoaded` would not be true, but using the conditional, it would be. This means that with the conditional, you can’t freely make assumptions behind the `hasLoaded` flag:
|
|
78
|
+
|
|
79
|
+
```jsx
|
|
80
|
+
{hasLoaded ? (
|
|
81
|
+
// with the conditional, you don't know which resources are available. with
|
|
82
|
+
// `dependsOn`, you do
|
|
83
|
+
) : null}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
That doesn’t mean that the conditional can’t be useful—it’s just that its use should be relegated to components that have two discrete forms—one in which the dependent prop is always present, and one in which the dependent prop is never present. If you’re unsure whether a prop might exist, notably because it comes from a providing resource, you should use `dependsOn`. A good example of when to use a conditional is in this fake component that sometimes fetches a user model and sometimes fetches an order model depending on the presence of an `orderId` prop:
|
|
87
|
+
|
|
88
|
+
```js
|
|
89
|
+
const getResources = (ResourceKeys, {userId, orderId}) => ({
|
|
90
|
+
...userId ? {[ResourceKeys.USER]: {options: {userId}} : {},
|
|
91
|
+
...!userId && orderId ? {
|
|
92
|
+
[ResourceKeys.ORDER]: {
|
|
93
|
+
noncritical: true,
|
|
94
|
+
data: {id: orderId}
|
|
95
|
+
}
|
|
96
|
+
} : {}
|
|
97
|
+
});
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
In this case, when the component is used as an order component (denoted by the presence of the `orderId` prop), we fetch the `order` resource. Otherwise, we don’t.
|
|
101
|
+
|
|
102
|
+
For all other uses of dependent resources, we should use `dependsOn`.
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
## Unfetched Resources
|
|
106
|
+
|
|
107
|
+
You may find, at some point in your application, that you have a `PUT` endpoint for a resource but no `GET`; the 'read portion' of the resource is received as part of some parent resource. For example, imagine you have an accounts resource at `/accounts/{account_id}`, whose response has a `config` property with some account configuration settings. To update the configuration, you make a `PUT` to `/accounts/{account_id}/config`. But reading comes from the parent resource. `resourcerer` supports this via a `providesModels` static property on the model:
|
|
108
|
+
|
|
109
|
+
```js
|
|
110
|
+
// resources_conifg.js
|
|
111
|
+
import {ResourceKeys, UnfetchedResources} from 'resourcerer';
|
|
112
|
+
|
|
113
|
+
ResourceKeys.add({
|
|
114
|
+
ACCOUNT: 'account',
|
|
115
|
+
ACCOUNT_CONFIG: 'accountConfig'
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
// add the ACCOUNT_CONFIG key to our set of UnfetchedResources
|
|
119
|
+
UnfetchedResources.add(ResourceKeys.ACCOUNT_CONFIG);
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
// account_model.js
|
|
123
|
+
export default class AccountModel extends Model {
|
|
124
|
+
url() {
|
|
125
|
+
return `/accounts/${this.accountId}`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
static cacheFields = ['accountId']
|
|
129
|
+
|
|
130
|
+
static providesModels = (accountModel, ResourceKeys) => [{
|
|
131
|
+
data: accountModel.get('config'),
|
|
132
|
+
modelKey: ResourceKeys.ACCOUNT_CONFIG,
|
|
133
|
+
options: {accountModel}
|
|
134
|
+
}]
|
|
135
|
+
})
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The `providesModels` property is a function that takes the parent model and the `ResourceKeys` as arguments and returns an array of resource configs. The resource configs have the same schema as the those used in our general executor functions. What this tells `resourcerer` to do is, after the parent model returns, instantiate the child model(s) and place them into the `ModelCache`. In other components, you can then access the model you know to exist in a `withResources` or `useResources` declaration:
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
// child_component.jsx, rendered only after the account model is known to return
|
|
142
|
+
@withResources((ResourceKeys, props) => ({[ResourceKeys.ACCOUNT_CONFIG]: {}}))
|
|
143
|
+
class ChildComponent extends React.Component {
|
|
144
|
+
// component has this.props.accountConfigModel from the cache!
|
|
145
|
+
onClickSomething() {
|
|
146
|
+
// and now you can update the config directly :)
|
|
147
|
+
this.props.accountConfigModel.save();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
In general, this should be used in cases where you can ascertain that the parent model has returned before trying to access the child model. However, if by chance it has not, and the child is not found in the cache, `resourcerer` will still not attempt to fetch it, because it is listed within the `UnfetchedResources` set. In that case, the model will get instantiated with no seed data and passed as a prop.
|
|
153
|
+
|
|
154
|
+
Also, note that the `modelKey` property is required here instead of optionally being inferred from the resource config's object property, as is the case in our general `useResources`/`withResources` declarations. This is because here, in contrast, the models are simply placed in the cache and not actually used as props for any component, so they don't need to be named. Accordingly, resource configs are also returned as a list here instead of an object.
|
|
155
|
+
|
|
156
|
+
The resource config objects within `providesModels` have the same schema, as mentioned, as normal. But they also accept an additional optional property, `shouldCache`, which is a function that takes the parent model and the resource config as an argument. If the function exists and returns false, the model will not get instantiated nor placed in the cache:
|
|
157
|
+
|
|
158
|
+
```js
|
|
159
|
+
// account_model.js
|
|
160
|
+
export default class AccountModel extends Model {
|
|
161
|
+
// ...
|
|
162
|
+
static cacheFields: ['accountId']
|
|
163
|
+
|
|
164
|
+
static providesModels = (accountModel, ResourceKeys) => [{
|
|
165
|
+
data: accountModel.get('config'),
|
|
166
|
+
modelKey: ResourceKeys.ACCOUNT_CONFIG,
|
|
167
|
+
options: {accountModel},
|
|
168
|
+
// if this returns false, account config won't get instantiated and placed in the ModelCache
|
|
169
|
+
shouldCache: (accountModel, config) => accountModel.get('state') === 'ACTIVE'
|
|
170
|
+
}]
|
|
171
|
+
})
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## Loading Overlays
|
|
175
|
+
|
|
176
|
+
You probably want to show loaders when you are moving between one model and the next. Because your resources are held as state, both exist in this intermediate state.
|
|
177
|
+
Both the hook and the HOC provide a `hasInitiallyLoaded` prop that is useful here. Here's an example of what it might look like (shown over one of [Sift](https://sift.com)'s Insights Charts):
|
|
178
|
+
|
|
179
|
+

|
|
180
|
+
|
|
181
|
+
Use it like:
|
|
182
|
+
|
|
183
|
+
```jsx
|
|
184
|
+
import {useResources} from 'resourcerer';
|
|
185
|
+
|
|
186
|
+
const getResources = ({TODOS}, props) => ({[TODOS]: {}});
|
|
187
|
+
|
|
188
|
+
export default function UserTodos(props) {
|
|
189
|
+
const {isLoading, hasInitiallyLoaded, todosCollection} = useResources(getResources, props);
|
|
190
|
+
|
|
191
|
+
return (
|
|
192
|
+
<div className='MyComponent'>
|
|
193
|
+
// it's up to you to make this an OverlayLoader or InlineLoader, if you so choose.
|
|
194
|
+
{isLoading ? <Loader /> : null}
|
|
195
|
+
// this will render once first loaded and remain rendered with a previous
|
|
196
|
+
// model even while in a loading state. when a new resource request returns,
|
|
197
|
+
// this will render with the updated model and the loader will be removed.
|
|
198
|
+
{hasInitiallyLoaded ? (
|
|
199
|
+
<ul>
|
|
200
|
+
{todosCollection.map((todoModel) => (
|
|
201
|
+
<li key={todoModel.id}>{todoModel.get('name')}</li>
|
|
202
|
+
))}
|
|
203
|
+
</ul>
|
|
204
|
+
) : null}
|
|
205
|
+
</div>
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## isOrWillBeLoading (`useResources` only)
|
|
211
|
+
|
|
212
|
+
Taking the previous example of [Loading Overlays](#loading-overlays) just a bit further, what if the todosCollection was 5000 entries long? Okay, you'd probably paginate. But that's not the point! Let's say it's an `<ExpensiveComponent />`, and as it is now, when we change loading states, the parent `MyComponent` would render `<ExpensiveComponent />` on every change, which will kill your UX. So let's wrap it in a `React.memo`!
|
|
213
|
+
|
|
214
|
+
But how do we tell `React.memo` when to not render? This is tricky for a couple of reasons:
|
|
215
|
+
|
|
216
|
+
* Because `useEffect`/`componentDidUpdate` occurs _after_ render, we actually have two renders we want to opt out of:
|
|
217
|
+
* parent props change
|
|
218
|
+
* render is called (opt out!) **See Note**
|
|
219
|
+
* resourcerer changes loaded state to loading from the change in props
|
|
220
|
+
* render is called (opt out!). parent shows the overlay loader
|
|
221
|
+
* request returns and loading state changes back to loaded
|
|
222
|
+
* render (we want this update!)
|
|
223
|
+
|
|
224
|
+
This is actually the reason why I am sad React did away with `componentWillReceiveProps` and does not offer an equivalent hook—using that instead would batch the props change and the loaded -> loading state change, and we'd only need to opt out of a single render. *sigh*. I digress.
|
|
225
|
+
|
|
226
|
+
* React.memo, unlike `shouldComponentUpdate`, does not change its `prevProps` if it skips a render. This makes sense if you think about `memo` being a higher-order-component—if the component doesn't update, its props don't change. But that makes it much harder to compare `prevProps` and `nextProps` when needing to skip two update cycles.
|
|
227
|
+
|
|
228
|
+
Enter `isOrWillBeLoading`. `isOrWillBeLoading` is a function returned by `useResources`/`withResources` that will take care of all these things for you, and you can invoke it in your `React.memo` [areEqual function](https://reactjs.org/docs/react-api.html#reactmemo). The previous example becomes:
|
|
229
|
+
|
|
230
|
+
```jsx
|
|
231
|
+
import ExpensiveComponent from 'components/expensive_component/expensive_component';
|
|
232
|
+
import {memo} from 'react';
|
|
233
|
+
import {useResources} from 'resourcerer';
|
|
234
|
+
|
|
235
|
+
const getResources = ({TODOS}, props) => ({[TODOS]: {}});
|
|
236
|
+
const MemoizedExpensiveComponent = memo(ExpensiveComponent, (prevProps, nextProps) => nextProps.isOrWillBeLoading());
|
|
237
|
+
|
|
238
|
+
export default function UserTodos(props) {
|
|
239
|
+
const {isLoading, isOrWillBeLoading, hasInitiallyLoaded} = useResources(getResources, props);
|
|
240
|
+
|
|
241
|
+
return (
|
|
242
|
+
<div className='MyComponent'>
|
|
243
|
+
{isLoading ? <Loader /> : null}
|
|
244
|
+
{hasInitiallyLoaded ? <MemoizedExpensiveComponent {...{isOrWillBeLoading}} /> : null}
|
|
245
|
+
</div>
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
**Note:** A future upgrade to this library will utilize a [render bailout](https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes) to remove this unnecessary render. The other two will still be required, though.
|
|
251
|
+
|
|
252
|
+
## Recaching newly-saved models
|
|
253
|
+
|
|
254
|
+
A common pattern when creating a new instance of a resource is to keep it in state until the user decides to explicitly save it. For example, when setting up a new
|
|
255
|
+
TODO, we might fill out a form with its name, all kept in state, at a deep-linkable RESTful url that might be `/todos/new`. After the user saves the TODO, we get a
|
|
256
|
+
server-provided `id` property and we might navigate to `/todos/12345`, where `12345` is the new id. This presents an inconvenience: at `/new` we want to read from
|
|
257
|
+
state, but at `/{id}` we want to read from the saved model (this is compounded if the UI allows the user to edit in-place).
|
|
258
|
+
|
|
259
|
+
To accomodate this scenario, `resourcerer` provides a means of re-caching a model instance the first time it receives an id. Thus you can use it with `fetch: false` like
|
|
260
|
+
this:
|
|
261
|
+
|
|
262
|
+
```jsx
|
|
263
|
+
import {useResources} from 'resourcerer';
|
|
264
|
+
|
|
265
|
+
const getResources = ({TODO}, props) => ({
|
|
266
|
+
[TODO]: {
|
|
267
|
+
data: {id: props.id},
|
|
268
|
+
fetch: !!props.id
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
export default function UserTodo(props) {
|
|
273
|
+
const {todoModel} = useResources(getResources, props),
|
|
274
|
+
onChange = (evt) => todoModel.set('name', evt.target.value),
|
|
275
|
+
onSubmit = todoModel.save()
|
|
276
|
+
.then(([model]) => !props.id ? navigate(`/todos/${model.id}`) : null)
|
|
277
|
+
.catch(() => notify('An error occurred');
|
|
278
|
+
|
|
279
|
+
return (
|
|
280
|
+
<form onSubmit={onSubmit}>
|
|
281
|
+
<label>
|
|
282
|
+
TODO:
|
|
283
|
+
<input name='name' onChange={onChange} value={todoModel.get('name')} />
|
|
284
|
+
</label>
|
|
285
|
+
<button>Save</button>
|
|
286
|
+
</form>
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
What's so nice about this example is that there's no balancing between React state and model state; in either case you read from
|
|
292
|
+
the model requested from `resourcerer`. When you load `/todos/new`, nothing is fetched and the model is created first client-side;
|
|
293
|
+
when you load `/todos/{todosId}`, the todos resource is first fetched. Both cases, however, are treated identically. And because of
|
|
294
|
+
`resourcerer`'s recaching, when you save for the first time and navigate from `/todos/new` to `/todos/{todosId}`, the model is
|
|
295
|
+
taken from its 'new' cache key and placed in its 'id' cache key, obviating the need to re-request the resource and moving seamlessly
|
|
296
|
+
from one to the other.
|
|
297
|
+
|
|
298
|
+
***NOTE:*** this is only for models requested individually and not as part of a larger collection. When adding a new model to a collection
|
|
299
|
+
that is fetched by `resourcerer`, you can accomplish the above without recaching.
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
# Collection
|
|
2
|
+
|
|
3
|
+
A collection is a client-side abstraction for the latest-saved server state of a list of objects (a model, by contrast, represents a single persisted object in that resource). A collection _must_ have one thing:
|
|
4
|
+
a `url`. This instance property can be a string literal or a function.
|
|
5
|
+
|
|
6
|
+
```js
|
|
7
|
+
class MyTodos extends Collection {
|
|
8
|
+
url = '/todos'
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
class MyTodos extends Collection {
|
|
12
|
+
url({subtype}) {
|
|
13
|
+
return `/todos/${subtype}`;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
A collection instance of the class created and registered in your [resourcerer config](https://github.com/noahgrant/resourcerer#nomenclature) will be returned by every `useResources` call that uses its model key from the [ModelMap](https://github.com/noahgrant/resourcerer#tutorial). You can read simply from it
|
|
19
|
+
by using [`Collection#toJSON`](#tojson) (the most common usage), but there are several other methods and properties in its interface you can customize in your collection definition or
|
|
20
|
+
that you might find useful in rendering your data-hydrated components.
|
|
21
|
+
|
|
22
|
+
## Properties
|
|
23
|
+
|
|
24
|
+
### `static` comparator
|
|
25
|
+
|
|
26
|
+
Add this on your Collection definition to tell it how it should sort its models. It can take three forms:
|
|
27
|
+
|
|
28
|
+
1. A string. In this case, it represents the model property to sort by.
|
|
29
|
+
2. A function with a single argument. In this case, it takes a model's data as an argument and returns the value by which it should sort.
|
|
30
|
+
3. A function with two arguments. This is used to sort the collection's models via the native [Array.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) method.
|
|
31
|
+
|
|
32
|
+
### length
|
|
33
|
+
|
|
34
|
+
This is an instance property that represents the number of models in the collection.
|
|
35
|
+
|
|
36
|
+
### `static` Model
|
|
37
|
+
|
|
38
|
+
Set this property if you want a collection's models to be an instance of a class other than the default Model
|
|
39
|
+
|
|
40
|
+
### `static` cacheFields
|
|
41
|
+
|
|
42
|
+
This property tells resourcerer how to determine whether to make a new request or to take a collection out of the cache. It is an array of strings or functions from which its cache key is calculated. See the [cacheKey](https://github.com/noahgrant/resourcerer#caching-resources-with-modelcache) section for more info.
|
|
43
|
+
|
|
44
|
+
### `static` cacheTimeout
|
|
45
|
+
`number`
|
|
46
|
+
|
|
47
|
+
The number of milliseconds to keep all collections of this class in the cache after all client components stop referencing it. Note that this is on a collection _class_ basis and not an _instance_ basis because the latter can introduce race conditions into your application.
|
|
48
|
+
|
|
49
|
+
### `static` measure
|
|
50
|
+
`boolean|function`
|
|
51
|
+
|
|
52
|
+
A boolean or function that accepts a [resource configuration object](https://github.com/noahgrant/resourcerer#nomenclature) and returns a boolean, telling resourcerer to track this collection's request time and report it via the `track` method setup in [configuration](https://github.com/noahgrant/resourcerer#configuring-resourcerer).
|
|
53
|
+
|
|
54
|
+
### `static` modelIdAttribute
|
|
55
|
+
|
|
56
|
+
Use this as a shortcut when you don't want to define a custom Model class just because the collection doesn't contain the default id field (which is `'id'`), ie:
|
|
57
|
+
|
|
58
|
+
```js
|
|
59
|
+
// the collection will index its models based on the `name` property instead of the default `id` property
|
|
60
|
+
static modelIdAttribute = 'name'
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
## Methods
|
|
66
|
+
|
|
67
|
+
### constructor
|
|
68
|
+
|
|
69
|
+
```js
|
|
70
|
+
constructor: void (models: Array<Object|Model>, options: object)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
The Collection's constructor gets passed any initial models, as well as the [options](https://github.com/noahgrant/resourcerer#options) from the executor function. Override this to add some custom logic or instance variables for the collection—just be sure to pass the arguments to its `.super()` call, as well:
|
|
74
|
+
|
|
75
|
+
```js
|
|
76
|
+
class MyCollection extends Collection {
|
|
77
|
+
constructor(models, options={}) {
|
|
78
|
+
super(models, options);
|
|
79
|
+
|
|
80
|
+
// initializing some variable to be used later
|
|
81
|
+
this.categoriesList = [];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
url({category}) {
|
|
85
|
+
return `/todos/${category}`;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Passing in a `Model` option or a `comparator` option to an instance's constructor will override the statically defined properties on its constructor. Other `options` fields (the ones passed from the executor function [options](https://github.com/noahgrant/resourcerer#options) property) are passed to the `url` as shown in the example above.
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
### add
|
|
94
|
+
```js
|
|
95
|
+
add: Collection (models: (Object|Model)|Array<Object|Model>, options: Object)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Add a new entry or list of entries into the collection. Each entry can be an object of data or a Model instance. Will trigger an update in all subscribed components unless the `trigger: true` option is passed. You can also pass a `parse: true` option to run the model through its [parse](/docs/model.md#parse) method before setting its properties. If an entry already exists on the collection, the new properties will get merged into its existing model.
|
|
99
|
+
|
|
100
|
+
### create
|
|
101
|
+
```js
|
|
102
|
+
create: Promise<[Model, Response]> (model: (Object|Model), options: Object)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Adds a new entry to the collection and persists it to the server. This is literally the equivalent to calling `collection.add()` and then `model.save()`. Because it also instantiates the new model, be sure to pass any path params you need in your url as the options argument (the same [options](https://github.com/noahgrant/resourcerer#options) in the resource config object). The returned Promise is the same as is returned from [Model#save](/docs/model.md#save). If the request errors, the model is auto-removed from the collection. Pass the `wait: true` option to wait to add the new model until after the save request returns. Subscribed components will update when the new entry is added as well as when the request returns.
|
|
106
|
+
|
|
107
|
+
***All .create() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
|
|
108
|
+
|
|
109
|
+
### fetch
|
|
110
|
+
```js
|
|
111
|
+
fetch: Promise<[Collection, Response]> (options: Object)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
This is the method that `resourcerer` uses internally to get server data and set its parsed response as models on the collection. This should rarely need to be used in your application. Subscribed components will update when the request returns.
|
|
115
|
+
|
|
116
|
+
***All .fetch() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
### get
|
|
120
|
+
```js
|
|
121
|
+
get: Model? (identifier: string|number)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Collections index their Model instances by either the Model's [`idAttribute`](/docs/model.md#static-idattribute) or, equivalently as a shortcut, by the collection's own static [`modelIdAttribute`](#static-modelidattribute) property. The `.get()` method takes an id value and returns the quick-lookup model instance if one exists.
|
|
125
|
+
|
|
126
|
+
### has
|
|
127
|
+
```js
|
|
128
|
+
has: boolean (identifier: string|number|Model|object)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Returns whether or not a model exists in a collection. You can pass the model instance itself, a model's data, or a model's id.
|
|
132
|
+
|
|
133
|
+
### parse
|
|
134
|
+
```js
|
|
135
|
+
parse: Array<Object> (response: any)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
This method takes in the raw server data response and should return the data in the form that should be set on the Collection. It defaults to the identity function, which might suffice for many endpoints. Override this for your custom needs. For example, for some search results with some metadata (in an API that returns a JSON object), we want to set the results as the collection:
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
parse(response) {
|
|
142
|
+
this.totalResults = response.totalResults;
|
|
143
|
+
this.pageNumber = response.pageNumber;
|
|
144
|
+
this.resultsPerPage = response.resultsPerPage;
|
|
145
|
+
|
|
146
|
+
return response.results;
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### remove
|
|
151
|
+
```js
|
|
152
|
+
remove: Collection (models: (Object|Model)|Array<Object|Model>, options: Object)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Use this to remove a model or models from the collection, which should not often be needed. You can pass in anything or a list of anything that can be accepted via [.get()](#get). Pass in `silent: true` for subscribed components _not_ to get rerendered.
|
|
156
|
+
|
|
157
|
+
### reset
|
|
158
|
+
```js
|
|
159
|
+
reset: Collection (models: Array<Object|Model>, options: Object)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Removes all models and their references from a collection and replaces them with the models passed in. Pass in `silent: true` for subscribed components _not_ to get rerendered, and `parse: true` to have data get parsed before being set on their respective models.
|
|
163
|
+
|
|
164
|
+
### set
|
|
165
|
+
```js
|
|
166
|
+
set: Collection (models: (Object|Model)|Array<Object|Model>, options: Object)
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
This is the method that many other write methods (`add`, `remove`, `save`, `reset`, etc) use under the hood, and it should _rarely if ever_ need to be used directly in your application. Sets new data as models and merges existing data with their models, and sorts as necessary. Pass in `silent: true` for subscribed components _not_ to get rerendered, and `parse: true` to have data get parsed before being set on their respective models.
|
|
170
|
+
|
|
171
|
+
### sync
|
|
172
|
+
This is just a proxy for the [sync](/lib/sync.js) module. Its behavior shouldn't be overridden, but it may be useful to wrap it for custom behavior, ie:
|
|
173
|
+
|
|
174
|
+
```js
|
|
175
|
+
Collection.sync = Model.sync = function(model, options) {
|
|
176
|
+
// custom logic...
|
|
177
|
+
|
|
178
|
+
// defer again to the sync module
|
|
179
|
+
return sync(this, options);
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### toJSON
|
|
184
|
+
```js
|
|
185
|
+
toJSON: Array<Object> ()
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Returns each model's data objects in a new array.
|
|
189
|
+
|
|
190
|
+
## Utility instance methods
|
|
191
|
+
|
|
192
|
+
### at
|
|
193
|
+
```js
|
|
194
|
+
at: Model (index: number)
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
Returns the model at a given index in the collection. Index can be negative to count backwards from the end.
|
|
198
|
+
|
|
199
|
+
### filter
|
|
200
|
+
```js
|
|
201
|
+
filter: Array<Model> (predicate: function)
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Same signature as Array.prototype.filter across a collection's models.
|
|
205
|
+
|
|
206
|
+
### find
|
|
207
|
+
```js
|
|
208
|
+
find: Model? (predicate: function)
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Same signature as Array.prototype.find across a collection's models.
|
|
212
|
+
|
|
213
|
+
### findWhere
|
|
214
|
+
```js
|
|
215
|
+
findWhere: Model? (attrs: object)
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
Returns the model matching the attributes passed in, or undefined if no match is found. Like `.find` but a shorthand that uses matching attribute values instead of a predicate function.
|
|
219
|
+
|
|
220
|
+
### map
|
|
221
|
+
```js
|
|
222
|
+
map: Array<any> (predicate: function)
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Same signature as Array.prototype.map across a collection's models.
|
|
226
|
+
|
|
227
|
+
### pluck
|
|
228
|
+
```js
|
|
229
|
+
pluck: Array<any> (attribute: string)
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Returns a list of the specified attribute value for all models.
|
|
233
|
+
|
|
234
|
+
### slice
|
|
235
|
+
```js
|
|
236
|
+
slice: Array<Model> (startIndex:number[, endIndex: number])
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Same signature as Array.prototype.slice across a collection's models.
|
|
240
|
+
|
|
241
|
+
### where
|
|
242
|
+
```js
|
|
243
|
+
where: Array<Model> (attrs: object)
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Returns a list of models matching the data values passed in. Like `.filter` but a shorthand that uses matching data values instead of a predicate function.
|
package/docs/model.md
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# Model
|
|
2
|
+
|
|
3
|
+
A model is a client-side abstraction for a latest-saved server state of an object (a collection, by contrast, represents a list of models). A model _must_ have one thing:
|
|
4
|
+
a `url`. This can come in several forms:
|
|
5
|
+
|
|
6
|
+
* a string literal
|
|
7
|
+
|
|
8
|
+
```js
|
|
9
|
+
class MyModel extends Model {
|
|
10
|
+
url = '/endpoint'
|
|
11
|
+
}
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
* a function
|
|
15
|
+
|
|
16
|
+
```js
|
|
17
|
+
class MyModel extends Model {
|
|
18
|
+
url() {
|
|
19
|
+
return '/endpoint';
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
* from the model's collection. in this case, no `url` property on the model is needed, and the model's id will be URL-encoded and appended to the collection's url.
|
|
25
|
+
|
|
26
|
+
* a `urlRoot` property. use this when a model is not part of a collection but when passed an id, you'd still like the id to be URL-encoded and appended to the root.
|
|
27
|
+
|
|
28
|
+
```js
|
|
29
|
+
class MyModel extends Model {
|
|
30
|
+
// with an id of '12345', requests will be made to /endpoint/12345.
|
|
31
|
+
urlRoot() {
|
|
32
|
+
return '/endpoint';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
A model instance of the class created and registered in your [resourcerer config](https://github.com/noahgrant/resourcerer#nomenclature) will be returned by every `useResources` call that uses its model key. You can read simply from it
|
|
38
|
+
by using [Model#toJSON](#tojson) (the most common usage), but there are several other methods and properties in its interface you can customize in your collection definition or
|
|
39
|
+
that you might find useful in rendering your data-hydrated components.
|
|
40
|
+
|
|
41
|
+
## Properties
|
|
42
|
+
|
|
43
|
+
### `static` cacheFields
|
|
44
|
+
`Array<string|function>`
|
|
45
|
+
|
|
46
|
+
This property tells resourcerer how to determine whether to make a new request or to take a model out of the cache. It is an array of strings or functions from which its cache key is calculated. See the [cacheKey](https://github.com/noahgrant/resourcerer#caching-resources-with-modelcache) section for more info.
|
|
47
|
+
|
|
48
|
+
### `static` cacheTimeout
|
|
49
|
+
`number`
|
|
50
|
+
|
|
51
|
+
The number of milliseconds to keep all models of this class in the cache after all client components stop referencing it. Note that this is on a model _class_ basis and not an _instance_ basis because the latter can introduce race conditions into your application.
|
|
52
|
+
|
|
53
|
+
### `static` idAttribute
|
|
54
|
+
`string`. Default: `'id'`.
|
|
55
|
+
|
|
56
|
+
Override this to be the property name of the Model's unique identifier if it something other than `'id'`. Each model instance will get an `id` instance property that will be equal to that value. i.e. if the Model class has `static idAttribute = 'email'` and the Model is instantiated with `{email: 'noah@gmail.com'}`, then `model.id === 'noah@gmail.com'`.
|
|
57
|
+
|
|
58
|
+
### `static` defaults
|
|
59
|
+
`object|function`
|
|
60
|
+
|
|
61
|
+
An object or function that returns object with attribute keys and their default values. If set, then when the model is instantiated, any missing data get set to these values.
|
|
62
|
+
|
|
63
|
+
### `static` measure
|
|
64
|
+
`boolean|function`
|
|
65
|
+
|
|
66
|
+
A boolean or function that accepts a [resource configuration object](https://github.com/noahgrant/resourcerer#nomenclature) and returns a boolean, telling resourcerer to track this model's request time and report it via the `track` method setup in [configuration](https://github.com/noahgrant/resourcerer#configuring-resourcerer).
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
## Methods
|
|
71
|
+
|
|
72
|
+
### constructor
|
|
73
|
+
|
|
74
|
+
```js
|
|
75
|
+
constructor: void (initialData: Object, options: object)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The Model's constructor gets passed any initial data, as well as the [options](https://github.com/noahgrant/resourcerer#options) from the executor function. Override this to add some custom logic or instance variables for the model—just be sure to pass the arguments to its `.super()` call, as well:
|
|
79
|
+
|
|
80
|
+
```js
|
|
81
|
+
class MyModel extends Model {
|
|
82
|
+
constructor(initialData, options={}) {
|
|
83
|
+
super(initialData, options);
|
|
84
|
+
|
|
85
|
+
// custom logic
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
url({category}) {
|
|
89
|
+
return `/todos/${category}/${this.id}`;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Note that `this.id` is automatically set to whichever value is passed in at the [`idAttribute`](#static-idattribute) key (default: 'id'). Pass the `parse: true` option to have the data get run through the Model's `parse` method before getting set. Other [options](https://github.com/noahgrant/resourcerer#options) fields from the executor function are passed to the `url` as shown in the example above.
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
### toJSON
|
|
98
|
+
```js
|
|
99
|
+
toJSON: Object ()
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Returns the model's data in a new object.
|
|
103
|
+
|
|
104
|
+
### get
|
|
105
|
+
```js
|
|
106
|
+
get: any (attribute: string)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Returns the value at the given attribute key.
|
|
110
|
+
|
|
111
|
+
### has
|
|
112
|
+
```js
|
|
113
|
+
has: boolean (attribute: string)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Returns true if the model has a defined value at the given attribute key
|
|
117
|
+
|
|
118
|
+
### isNew
|
|
119
|
+
```js
|
|
120
|
+
isNew: boolean ()
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
By default, a model is considered 'new' if it does not have an id (or a value at the [`idAttribute`](#static-idattribute) proeprty. It is used to determine:
|
|
124
|
+
|
|
125
|
+
1. Whether to send a POST (new) or a PUT (not new) request when calling [`.save()`](#save)
|
|
126
|
+
2. Whether to send a request at all when calling [`.destroy()`](#destroy)
|
|
127
|
+
|
|
128
|
+
Use this to your advantage when you inevitably come across some orphan endpoints that are not super REST-y. Override your Model class to force all `.save` calls to POST by, for example:
|
|
129
|
+
|
|
130
|
+
```js
|
|
131
|
+
isNew() {
|
|
132
|
+
// will always POST
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### parse
|
|
138
|
+
```js
|
|
139
|
+
parse: object (response: any)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
This method takes in the raw server data response and should return the data in the form that should be set on the Model. It defaults to the identity function, which might suffice for many endpoints. Override this for your custom needs. For example, maybe your server overly-nests the resource in a `schema` property:
|
|
143
|
+
|
|
144
|
+
```js
|
|
145
|
+
parse(response) {
|
|
146
|
+
return response.data.schema;
|
|
147
|
+
}
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### set
|
|
151
|
+
```js
|
|
152
|
+
set: Model (data: object, options: object)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
This is the main avenue by which a model's properties get values assigned. It's called internally by several public methods, including `save`, `unset`, and `clear`. Pass a `silent: true` option for this not to trigger a re-render for subscribed components.
|
|
156
|
+
|
|
157
|
+
### unset
|
|
158
|
+
```js
|
|
159
|
+
unset: Model (attribute: string, options: object)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Removes the attribute from the model's data. Pass a `silent: true` option for this not to trigger a re-render for subscribed components.
|
|
163
|
+
|
|
164
|
+
### clear
|
|
165
|
+
```js
|
|
166
|
+
clear: Model (options: object)
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Removes all data from the model. Pass a `silent: true` option for this not to trigger a re-render for subscribed components.
|
|
170
|
+
|
|
171
|
+
### pick
|
|
172
|
+
```js
|
|
173
|
+
pick: object (...data: Array<string>)
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Handy helper method to only return a subset of a model's data, as opposed to the whole thing like [`.toJSON()`](#tojson) does.
|
|
177
|
+
|
|
178
|
+
### save
|
|
179
|
+
```js
|
|
180
|
+
save: Promise<[Model, Response]> (data: object, options: object)
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Use this to persist data mutations to the server. If [`.isNew()`](#isnew) is true, the request will be sent as a POST. Otherwise, it will be sent as a PUT with the whole resource, or a PATCH with only `data` sent over if the `patch: true` option is passed. When the request returns, the server data is passed through the [`.parse()`](#parse) method before being set on the model. Pass the `wait: true` option to wait to add the data until after the server responds. Subscribed components will update when the new entry is added as well as when the request returns. If the request errors, all changes will be reverted and components updated.
|
|
184
|
+
|
|
185
|
+
***All .save() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
|
|
186
|
+
|
|
187
|
+
### destroy
|
|
188
|
+
```js
|
|
189
|
+
destroy: Promise<[Model, Response]> (options: object)
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
Use this to remove the send a DELETE request at this model's url to the server. The model is removed from its collection if it belongs to one. If [`.isNew()`](#isnew) is false (signifying that the model was never persisted in the first place), a request is not sent, but the model is still removed from its collection. Pass the `wait: true` option to wait to remove the model until after the server responds. Subscribed components will update when the model is removed. If the request errors, the model will get added back to its collection and components will get updated.
|
|
193
|
+
|
|
194
|
+
***All .destroy() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
|
|
195
|
+
|
|
196
|
+
### fetch
|
|
197
|
+
```js
|
|
198
|
+
fetch: Promise<[Model, Response]> (options: Object)
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
This is the method that `resourcerer` uses internally to get server data and set its parsed response as models on the collection. This should rarely need to be used in your application. Subscribed components will update when the request returns.
|
|
202
|
+
|
|
203
|
+
***All .fetch() calls must have a .catch attached, even if the rejection is swallowed. Omitting one risks an uncaught Promise rejection exception if the request fails.***
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
## Testing Components that Use Resourcerer
|
|
2
|
+
|
|
3
|
+
When writing tests for components that use either the `useResources` hook or the `withResources` HOC, we want to be able to easily avoid any kind of async behavior with the data fetching—and ideally we don’t even need to stub out the `fetch` requests. One way to get around this is to pass all resources to your test component as props. When this happens, the fetching is bypassed, and the component will render synchronously with the resources present, no stubbing necessary! Here’s an example for a component called `UserTodosList` that requires both a usersCollection and a todosCollection:
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
import {Collection} from 'resourcerer';
|
|
7
|
+
|
|
8
|
+
// ...
|
|
9
|
+
const defaultProps = () => ({
|
|
10
|
+
todosCollection: new Collection(mockTodos),
|
|
11
|
+
usersCollection: new Collection(mockUsers),
|
|
12
|
+
userId: 'noah'
|
|
13
|
+
},
|
|
14
|
+
|
|
15
|
+
renderUserTodosList = (props={}) => render(<UserTodosList {...defaultProps()} {...props} />);
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
it('runs a test', () => {
|
|
19
|
+
// both resources are passed as props, so no fetching takes place, `hasLoaded` is always true,
|
|
20
|
+
// and the component is rendered synchronously!
|
|
21
|
+
var userTodosList = renderUserTodosList();
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### Changing resource loading states
|
|
26
|
+
|
|
27
|
+
When using `resourcerer`, you are using React function components that have no backing instances (and thus whose return from `render` is `null`). Therefore, we can't assert any prop values on components and we can't navigate a DOM tree the way we can when using classes. However, we can simply mock out `useResources` itself to test functionality. Because the `withResources` HOC also uses `useResources` under the hood, this will work when testing both. Here's an example (using [jest](https://jestjs.io/) and [react testing library](https://testing-library.com/docs/react-testing-library/intro/)) for testing how a component that uses `useResources` looks under a loading state:
|
|
28
|
+
|
|
29
|
+
```jsx
|
|
30
|
+
import * as resourcerer from 'resourcerer';
|
|
31
|
+
import {render} from '@testing-library/react';
|
|
32
|
+
|
|
33
|
+
// ...
|
|
34
|
+
it('shows a loader when in a loading state', () => {
|
|
35
|
+
jest.spyOn(resourcerer, 'useResources').mockImplementation((fn, props) => ({
|
|
36
|
+
...props,
|
|
37
|
+
hasLoaded: false,
|
|
38
|
+
isLoading: true
|
|
39
|
+
));
|
|
40
|
+
|
|
41
|
+
const {container} = render(<MyComponent />);
|
|
42
|
+
|
|
43
|
+
expect(container.querySelector('.Loader')).toBeInTheDocument();
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
This should solve most of your use cases; you can return any mocked info you want, such as a noncritical loading state. You can also mock out `setResourceState`:
|
|
48
|
+
|
|
49
|
+
```jsx
|
|
50
|
+
var setResourceMock = jest.fn();
|
|
51
|
+
|
|
52
|
+
jest.spyOn(resourcerer, 'useResources').mockImplementation((fn, props) => ({
|
|
53
|
+
...props,
|
|
54
|
+
setResourceState: setResourceMock
|
|
55
|
+
));
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Keep in mind that in this case the calls to `setResourceState` won't actually go through, and so state won't persist.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# Using resourcerer with TypeScript
|
|
2
|
+
|
|
3
|
+
_Note: TypeScript support is in beta. Please file any bugs._
|
|
4
|
+
|
|
5
|
+
Resourcerer is ⚡⚡⚡ with TypeScript, but requires one extra step in your config file:
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
// js/core/resourcerer-config.ts
|
|
9
|
+
import {ModelMap} from 'resourcerer';
|
|
10
|
+
import TodosCollection from 'js/models/todos-collection';
|
|
11
|
+
import UserTodosCollection from 'js/models/users-todos-collection';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Because the ModelMap is populated in user-land, we have to annotate its types here, as well.
|
|
15
|
+
* Add your model types to this interface declaration, which will be merged with the interface
|
|
16
|
+
* in the library.
|
|
17
|
+
*
|
|
18
|
+
* I wish we didn't have to do this duplication, and maybe there's a way to do it without, but
|
|
19
|
+
* I am not good enough at TypeScript to figure it out myself. If you can, please submit a PR!
|
|
20
|
+
*/
|
|
21
|
+
declare module 'resourcerer' {
|
|
22
|
+
export interface ModelMap {
|
|
23
|
+
todos: new () => TodosCollection,
|
|
24
|
+
userTodos: new () => UserTodosCollection,
|
|
25
|
+
// ...etc
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/ now add your models to the model map as normal
|
|
30
|
+
ModelMap.add({
|
|
31
|
+
todos: TodosCollection,
|
|
32
|
+
userTodos: UserTodosCollection,
|
|
33
|
+
// ...etc
|
|
34
|
+
});
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Note that you no longer need to add a resource key like `USER_TODOS` in the ModelMap, which would normally get
|
|
38
|
+
auto-magically turned into the camelCase `userTodos`. Since TypeScript will enforce correctness, you can just
|
|
39
|
+
use the string literal `userTodos` instead.
|
|
40
|
+
|
|
41
|
+
When defining your models, you can add schemas as generic types:
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
// js/models/todos-collection.ts
|
|
45
|
+
import {Collection} from 'resourcerer';
|
|
46
|
+
|
|
47
|
+
interface Todo {
|
|
48
|
+
id: string;
|
|
49
|
+
name: string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export default TodosCollection extends Collection<Todo> {
|
|
53
|
+
url() {
|
|
54
|
+
return '/todos';
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
and now you can use it in your components!
|
|
60
|
+
|
|
61
|
+
```tsx
|
|
62
|
+
import {type ExecutorFunction, useResources} from 'resourcerer';
|
|
63
|
+
|
|
64
|
+
// you don't need to worry about resourceKeys anymore, you can just use the
|
|
65
|
+
// string literal! TypeScript will enforce correctness
|
|
66
|
+
const getResources: ExecutorFunction = (resourceKeys, props) => ({todos: {}});
|
|
67
|
+
|
|
68
|
+
function MyComponent(props) {
|
|
69
|
+
const {
|
|
70
|
+
isLoading,
|
|
71
|
+
hasErrored,
|
|
72
|
+
hasLoaded,
|
|
73
|
+
// type: TodosCollection
|
|
74
|
+
todosCollection
|
|
75
|
+
} = useResources(getResources, props);
|
|
76
|
+
|
|
77
|
+
return (
|
|
78
|
+
<div className='MyComponent'>
|
|
79
|
+
{isLoading ? <Loader /> : null}
|
|
80
|
+
|
|
81
|
+
{hasErrored ? <ErrorMessage /> : null}
|
|
82
|
+
|
|
83
|
+
{hasLoaded ? (
|
|
84
|
+
<ul>
|
|
85
|
+
{/** id and name are registered as string types, hurray! */}
|
|
86
|
+
{todosCollection.toJSON().map(({id, name}) => (
|
|
87
|
+
<li key={id}>{name}</li>
|
|
88
|
+
))}
|
|
89
|
+
</ul>
|
|
90
|
+
) : null}
|
|
91
|
+
</div>
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
```
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// this will make CONST_CASE a camelCase but also leave camelCase alone
|
|
2
|
+
type Camelize<T extends string> = T extends `${infer A}_${infer B}` ?
|
|
3
|
+
`${Lowercase<A>}${Camelize<Capitalize<B>>}` :
|
|
4
|
+
T extends Uppercase<T> ?
|
|
5
|
+
Capitalize<Lowercase<T>> :
|
|
6
|
+
T extends `${infer A}${Uppercase<infer B>}` ?
|
|
7
|
+
Lowercase<T> :
|
|
8
|
+
T;
|
|
9
|
+
|
|
10
|
+
declare module 'resourcerer' {
|
|
11
|
+
type SyncOptions = {
|
|
12
|
+
attrs?: Record<string, any>;
|
|
13
|
+
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
14
|
+
params?: Record<string, any>;
|
|
15
|
+
url?: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
type SetOptions = {
|
|
19
|
+
silent?: boolean;
|
|
20
|
+
unset?: boolean;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
// for collection.set
|
|
24
|
+
type CSetOptions = {
|
|
25
|
+
parse?: boolean;
|
|
26
|
+
silent?: boolean;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
declare class Model<T extends Record<string, any> = {[key: string]: any}> {
|
|
30
|
+
constructor(attrs?: T, options?: Record<string, any> & SetOptions): Model;
|
|
31
|
+
|
|
32
|
+
// TODO: need to reference idAttribute here
|
|
33
|
+
id: T extends {id: string} ? string : string | undefined;
|
|
34
|
+
|
|
35
|
+
get<K extends keyof T>(key: K): T[K];
|
|
36
|
+
|
|
37
|
+
has(key: keyof T): boolean;
|
|
38
|
+
|
|
39
|
+
clear(options?: SetOptions): Model;
|
|
40
|
+
|
|
41
|
+
unset(attr: keyof T, options?: SetOptions): Model;
|
|
42
|
+
|
|
43
|
+
parse(response: Record<string, any>): T;
|
|
44
|
+
|
|
45
|
+
pick<K extends keyof T>(...attrs: K[]): Pick<T, K>;
|
|
46
|
+
|
|
47
|
+
set(attrs: Partial<T>, options?: SetOptions): Model;
|
|
48
|
+
|
|
49
|
+
fetch(options?: {parse?: boolean} & SyncOptions & SetOptions): Promise<[Model, Response]>;
|
|
50
|
+
|
|
51
|
+
save(attrs: Partial<T>, options?: {wait?: boolean} & SyncOptions & SetOptions):
|
|
52
|
+
Promise<[Model, Response]>;
|
|
53
|
+
|
|
54
|
+
destroy(options?: {wait?: boolean} & SyncOptions & SetOptions): Promise<[Model, Response]>;
|
|
55
|
+
|
|
56
|
+
isNew(): boolean;
|
|
57
|
+
|
|
58
|
+
toJSON(): T;
|
|
59
|
+
|
|
60
|
+
url(): string;
|
|
61
|
+
|
|
62
|
+
urlRoot(): string;
|
|
63
|
+
|
|
64
|
+
static cacheFields: Array<string | ((attrs: T) => Record<string, any>)>;
|
|
65
|
+
|
|
66
|
+
static cacheTimeout: number;
|
|
67
|
+
|
|
68
|
+
static idAttribute: string;
|
|
69
|
+
|
|
70
|
+
static defaults: Record<keyof T, any> | (() => Record<keyof T, any>);
|
|
71
|
+
|
|
72
|
+
static measure: boolean | (() => void);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
type ModelArg<A> = Model<A> | Record<string, any>;
|
|
76
|
+
|
|
77
|
+
declare class Collection<
|
|
78
|
+
T extends Record<string, any> = {[key: string]: any},
|
|
79
|
+
O extends Record<string, any> & CSetOptions = {[key: string]: any}
|
|
80
|
+
> {
|
|
81
|
+
constructor(
|
|
82
|
+
models?: ModelArg<T> | ModelArg<T>[],
|
|
83
|
+
options?: O
|
|
84
|
+
): Collection;
|
|
85
|
+
|
|
86
|
+
length: number;
|
|
87
|
+
|
|
88
|
+
add(models: ModelArg<T> | ModelArg<T>[], options: CSetOptions): Collection;
|
|
89
|
+
|
|
90
|
+
remove(models: ModelArg<T> | ModelArg<T>[]): Collection;
|
|
91
|
+
|
|
92
|
+
set(models: ModelArg<T> | ModelArg<T>[], options: CSetOptions): Collection;
|
|
93
|
+
|
|
94
|
+
reset(models: ModelArg<T>[], options: CSetOptions): Collection;
|
|
95
|
+
|
|
96
|
+
get(id?: string | ModelArg<T>): Model<T> | undefined;
|
|
97
|
+
|
|
98
|
+
has(id?: string | ModelArg<T>): boolean;
|
|
99
|
+
|
|
100
|
+
at(index: number): Model<T> | undefined;
|
|
101
|
+
|
|
102
|
+
toJSON(): T[];
|
|
103
|
+
|
|
104
|
+
sort(): Collection;
|
|
105
|
+
|
|
106
|
+
map<R = any>(predicate: (model: Model<T>) => R): R[];
|
|
107
|
+
|
|
108
|
+
find(predicate: (model: Model<T>) => boolean): Model<T>;
|
|
109
|
+
|
|
110
|
+
filter(predicate: (model: Model<T>) => boolean): Model<T>[];
|
|
111
|
+
|
|
112
|
+
findWhere<K extends keyof T>(attrs: Record<K, T[K]>): Model<T>;
|
|
113
|
+
|
|
114
|
+
where<K extends keyof T, B extends boolean = false>(attrs: Record<K, T[K]>, find?: B):
|
|
115
|
+
B extends true ?
|
|
116
|
+
Model<T> :
|
|
117
|
+
Model<T>[];
|
|
118
|
+
|
|
119
|
+
pluck<K extends keyof T>(prop: K): Record<K, T[K]>[];
|
|
120
|
+
|
|
121
|
+
slice(start: number, end?: number): ModelArg<T>[];
|
|
122
|
+
|
|
123
|
+
parse(response: Record<string, any> | any[], options?: Record<string, any>): Array<T>;
|
|
124
|
+
|
|
125
|
+
create(
|
|
126
|
+
model: ModelArg<T>,
|
|
127
|
+
options?: {wait?: boolean} & SyncOptions & CSetOptions
|
|
128
|
+
): Promise<[Collection, Response]>;
|
|
129
|
+
|
|
130
|
+
fetch(options?: {parse?: boolean} & SyncOptions & CSetOptions): Promise<[Collection, Response]>;
|
|
131
|
+
|
|
132
|
+
url(urlOptions?: O): string;
|
|
133
|
+
|
|
134
|
+
static cacheFields: Array<string | ((attrs: T) => Record<string, any>)>;
|
|
135
|
+
|
|
136
|
+
static modelIdAttribute: string;
|
|
137
|
+
|
|
138
|
+
static measure: boolean | (() => void);
|
|
139
|
+
|
|
140
|
+
static cacheTimeout: number;
|
|
141
|
+
|
|
142
|
+
static comparator: string |
|
|
143
|
+
((arg: Model<T>) => number | string) |
|
|
144
|
+
((arg1: Model<T>, arg2: Model<T>) => number);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
type LoadingTypes = 'loading' | 'loaded' | 'errored' | 'pending';
|
|
148
|
+
|
|
149
|
+
// this will be filled out by users
|
|
150
|
+
export interface ModelMap {}
|
|
151
|
+
|
|
152
|
+
type ResourceKeys = {
|
|
153
|
+
[key in keyof ModelMap]: key extends string ? Camelize<Uncapitalize<key>> : key
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
type ModelProperty<Str extends string> = {[key: `${Str}Model`]: Model};
|
|
157
|
+
type CollectionProperty<Str extends string> = {[key: `${Str}Collection`]: Collection};
|
|
158
|
+
|
|
159
|
+
interface UseResourcesResponse {
|
|
160
|
+
isLoading: boolean;
|
|
161
|
+
hasErrored: boolean;
|
|
162
|
+
hasLoaded: boolean;
|
|
163
|
+
hasInitiallyLoaded: boolean;
|
|
164
|
+
refetch: (fn: (keys: {[key: string]: ResourceKeys}) => ResourceKeys[]) => void;
|
|
165
|
+
setResourceState(newState: {[key: string]: any}): void;
|
|
166
|
+
isOrWillBeLoading(): boolean;
|
|
167
|
+
[key: `${string}LoadingState`]: LoadingTypes;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
declare function haveAllLoaded(loadingStates: LoadingTypes | LoadingTypes[]): boolean;
|
|
171
|
+
declare function haveAnyErrored(loadingStates: LoadingTypes | LoadingTypes[]): boolean;
|
|
172
|
+
declare function areAnyLoading(loadingStates: LoadingTypes | LoadingTypes[]): boolean;
|
|
173
|
+
declare function areAnyPending(loadingStates: LoadingTypes | LoadingTypes[]): boolean;
|
|
174
|
+
|
|
175
|
+
type ResourceConfigObj = {
|
|
176
|
+
data?: {[key: string]: any};
|
|
177
|
+
dependsOn?: string[];
|
|
178
|
+
force?: boolean;
|
|
179
|
+
lazy?: boolean;
|
|
180
|
+
modelKey?: ResourceKeys;
|
|
181
|
+
noncritical?: boolean;
|
|
182
|
+
options?: {[key: string]: any};
|
|
183
|
+
params?: {[key: string]: any};
|
|
184
|
+
prefetches?: {[key: string]: any}[];
|
|
185
|
+
provides?: (model: Model | Collection) => {[key: string]: any};
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
type ResourceValues = Extract<typeof ResourceKeys[keyof typeof ResourceKeys], string>;
|
|
189
|
+
type InvertedResourceKeys = {[Key in keyof ResourceKeys as ResourceKeys[Key]]: Key};
|
|
190
|
+
|
|
191
|
+
// TODO: how to only use those keys that were passed, not the whole resourcekeys obj
|
|
192
|
+
export type ExecutorFunction = (
|
|
193
|
+
ResourceKeys_: ResourceKeys,
|
|
194
|
+
props: {[key: string]: any}
|
|
195
|
+
) => Partial<Record<ResourceValues, ResourceConfigObj>>;
|
|
196
|
+
|
|
197
|
+
type WithModelSuffix<K, C> = C extends Collection ? `${K}Collection` : `${K}Model`;
|
|
198
|
+
|
|
199
|
+
declare function useResources(
|
|
200
|
+
getResources: ExecutorFunction,
|
|
201
|
+
props: {[key: string]: any}
|
|
202
|
+
): UseResourcesResponse & {
|
|
203
|
+
[Key in keyof Required<ReturnType<ExecutorFunction>> as
|
|
204
|
+
WithModelSuffix<Key, InstanceType<ModelMap[InvertedResourceKeys[Key]]>>]:
|
|
205
|
+
InstanceType<ModelMap[InvertedResourceKeys[Key]]>
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
type test = ReturnType<ExecutorFunction>;
|
|
209
|
+
|
|
210
|
+
export interface ModelCache {
|
|
211
|
+
get(key: string): Model | Collection | undefined;
|
|
212
|
+
put(key: string, model: Model | Collection, component: any): void;
|
|
213
|
+
register(key: string, component: any): void;
|
|
214
|
+
unregister(component: any, ...keys: string[]): void;
|
|
215
|
+
remove(key: string): void;
|
|
216
|
+
__removeAll__(): void;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
interface TrackOptions {
|
|
220
|
+
Resource: string;
|
|
221
|
+
params: {[key: string]: any};
|
|
222
|
+
options: {[key: string]: any};
|
|
223
|
+
duration: number;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
interface RequestPrefilter {
|
|
227
|
+
// TODO
|
|
228
|
+
error: (...args: any[]) => any;
|
|
229
|
+
headers: {[key: string]: string};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
type ResourcerConfigOptions = {
|
|
233
|
+
cacheGracePeriod?: number;
|
|
234
|
+
errorBoundaryChild?: any;
|
|
235
|
+
log?: (err: Error) => void;
|
|
236
|
+
queryParamsPropName?: string;
|
|
237
|
+
stringify?: (params: {[key: string]: any}, options: {[key: string]: any}) => string;
|
|
238
|
+
track?: (name: string, options: TrackOptions) => void;
|
|
239
|
+
prefilter?: (options: {[key: string]: any}) => RequestPrefilter;
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
let ResourceKeys: ResourceKeys & {add(keys: Partial<ResourceKeys>): void;};
|
|
243
|
+
let ResourcesConfig: ResourcerConfigOptions & {set: (options: ResourcerConfigOptions) => void;};
|
|
244
|
+
let ModelMap: ModelMap & {add(keys: ModelMap): void;};
|
|
245
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "resourcerer",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"repository": "github.com/noahgrant/resourcerer",
|
|
5
5
|
"description": "Declarative data-fetching and caching framework for React",
|
|
6
6
|
"keywords": [
|
|
@@ -9,9 +9,11 @@
|
|
|
9
9
|
],
|
|
10
10
|
"files": [
|
|
11
11
|
"*.js",
|
|
12
|
+
"index.d.ts",
|
|
12
13
|
"lib/*.js",
|
|
13
14
|
"test/*.js",
|
|
14
|
-
"*.md"
|
|
15
|
+
"*.md",
|
|
16
|
+
"docs/*.md"
|
|
15
17
|
],
|
|
16
18
|
"main": "index.js",
|
|
17
19
|
"scripts": {
|