resourcerer 2.2.2 → 2.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +16 -8
- package/README.md +35 -20
- package/build/lib/canonical-model.d.ts +2 -0
- package/build/lib/canonical-model.js +10 -0
- package/build/lib/collection.d.ts +4 -2
- package/build/lib/collection.js +4 -0
- package/build/lib/model-cache.d.ts +3 -2
- package/build/lib/model.d.ts +5 -2
- package/build/lib/model.js +34 -0
- package/build/lib/request.d.ts +1 -0
- package/build/lib/types.d.ts +2 -1
- package/docs/advanced_topics.md +15 -1
- package/docs/collection.md +21 -5
- package/docs/migrating_to_2.0.md +4 -2
- package/docs/model.md +24 -3
- package/docs/testing_components.md +7 -6
- package/docs/typescript.md +2 -2
- package/package.json +1 -1
- package/resourcerer.d.ts +2 -0
- package/test/canonical-model.test.js +40 -1
- package/test/collection.test.js +11 -0
- package/test/model.test.js +295 -0
package/CONTRIBUTING.md
CHANGED
|
@@ -2,36 +2,44 @@
|
|
|
2
2
|
|
|
3
3
|
Please use the following guidelines when contributing to this repository:
|
|
4
4
|
|
|
5
|
-
* Use
|
|
5
|
+
* Use GitHub issues to report bugs and feature requests. For help debugging, please use StackOverflow.
|
|
6
6
|
|
|
7
|
-
* Pull requests should be made to
|
|
7
|
+
* Pull requests should be made to `main`. Before sending one for a feature or bug fix, be sure to add [tests](#tests). Please update documentation when your change affects the public API or documented behavior.
|
|
8
8
|
|
|
9
9
|
* Use the same coding style as the rest of the codebase; besides passing tests, all changes must also pass style checks.
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
## Conduct
|
|
13
|
-
See our [Code of Conduct](https://github.com/
|
|
13
|
+
See our [Code of Conduct](https://github.com/noahgrant/resourcerer/CODE_OF_CONDUCT.md) page.
|
|
14
14
|
|
|
15
15
|
|
|
16
16
|
## Clone the repo
|
|
17
17
|
To get started in development, clone the repository and install dependencies:
|
|
18
|
-
|
|
18
|
+
|
|
19
19
|
```sh
|
|
20
|
-
$ git clone git@github.com:
|
|
20
|
+
$ git clone git@github.com:noahgrant/resourcerer.git
|
|
21
21
|
$ cd resourcerer
|
|
22
22
|
$ npm i
|
|
23
23
|
```
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
## Tests
|
|
27
|
-
|
|
27
|
+
Tests run with [Vitest](https://vitest.dev/). Trigger them with:
|
|
28
28
|
|
|
29
29
|
`$ npm test`
|
|
30
30
|
|
|
31
|
-
|
|
31
|
+
You can run the TypeScript typechecker with:
|
|
32
|
+
|
|
33
|
+
`$ npm run typecheck`
|
|
34
|
+
|
|
35
|
+
You can run the linter with:
|
|
32
36
|
|
|
33
37
|
`$ npm run lint`
|
|
34
38
|
|
|
35
|
-
To run
|
|
39
|
+
To run typecheck, tests, and lint together:
|
|
36
40
|
|
|
37
41
|
`$ npm run checks`
|
|
42
|
+
|
|
43
|
+
For a watch mode during development:
|
|
44
|
+
|
|
45
|
+
`$ npm run test:watch`
|
package/README.md
CHANGED
|
@@ -21,7 +21,7 @@ Additional features include:
|
|
|
21
21
|
* forced cache invalidation
|
|
22
22
|
* updating a component when a resource updates
|
|
23
23
|
* zero dependencies
|
|
24
|
-
*
|
|
24
|
+
* under 10kB gzipped!
|
|
25
25
|
|
|
26
26
|
Getting started is easy:
|
|
27
27
|
|
|
@@ -136,7 +136,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
|
|
|
136
136
|
1. [Changing Props](#changing-props)
|
|
137
137
|
1. [Common Resource Config Options](#common-resource-config-options)
|
|
138
138
|
1. [params](#params)
|
|
139
|
-
1. [
|
|
139
|
+
1. [path](#path)
|
|
140
140
|
1. [noncritical](#noncritical)
|
|
141
141
|
1. [force](#force)
|
|
142
142
|
1. [Custom Resource Names](#custom-resource-names)
|
|
@@ -144,19 +144,20 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
|
|
|
144
144
|
1. [data](#data)
|
|
145
145
|
1. [lazy](#lazy)
|
|
146
146
|
1. [minDuration](#minduration)
|
|
147
|
+
1. [fetch](#fetch)
|
|
147
148
|
1. [dependsOn](#dependson)
|
|
148
149
|
1. [provides](#provides)
|
|
149
150
|
1. [Data mutations](#data-mutations)
|
|
150
151
|
1. [Serial Requests](#serial-requests)
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
152
|
+
1. [Canonical Models](#canonical-models)
|
|
153
|
+
1. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
|
|
154
|
+
1. [Using resourcerer with TypeScript](docs/typescript.md)
|
|
155
|
+
1. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
|
|
156
|
+
1. [Declarative Cache Keys](#declarative-cache-keys)
|
|
157
|
+
1. [Prefetch on Hover](#prefetch-on-hover)
|
|
158
|
+
1. [Refetching](#refetching)
|
|
159
|
+
1. [Cache Invalidation](#cache-invalidation)
|
|
160
|
+
1. [Tracking Request Times](#tracking-request-times)
|
|
160
161
|
1. [Configuring resourcerer](#configuring-resourcerer)
|
|
161
162
|
1. [FAQs](#faqs)
|
|
162
163
|
1. [Migrating to v2.0](#migrating-to-v20)
|
|
@@ -166,7 +167,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
|
|
|
166
167
|
|
|
167
168
|
`$ npm i resourcerer` or `yarn add resourcerer`
|
|
168
169
|
|
|
169
|
-
`resourcerer` requires
|
|
170
|
+
`resourcerer` requires React >= 16.14 (peer range includes React 17, 18, and 19) but has no external dependencies.
|
|
170
171
|
|
|
171
172
|
Note: Resourcerer is written in TypeScript and is compiled to ESNext. It does no further transpiling—including `import`/`export`.
|
|
172
173
|
If you are using TypeScript yourself, this won't be a problem. If you're not, and you're not babelifying (or similar) your `node_modules` folder, you'll need to make an exception for this package, ie:
|
|
@@ -256,7 +257,8 @@ Back to the executor function. In the example above, you see it returns an objec
|
|
|
256
257
|
Of course, in our initial example, the `todosCollection` won’t be populated with data immediately since, after all, the resource has to be fetched from the API. Some of the most **significant** and most common React UI states we utilize are whether a component’s critical resources have loaded entirely, whether any are still loading, or whether any have errored out. This is how we can appropriately cover our bases—i.e., we can ensure the component shows a loader while the resource is still in route, or if something goes wrong, we can ensure the component will still fail gracefully and not break the layout. To address these concerns, the `useResources` hook/`withResources` HOC gives you several loading state helper props. From our last example:
|
|
257
258
|
|
|
258
259
|
|
|
259
|
-
- `todosLoadingState` (can be equal to any of the [LoadingStates constants](https://github.com/noahgrant/resourcerer/blob/
|
|
260
|
+
- `todosLoadingState` (can be equal to any of the [LoadingStates constants](https://github.com/noahgrant/resourcerer/blob/main/lib/types.ts#L4). There will be one for each resource, and the property names will be equal to `${resourceKey}LoadingState`)
|
|
261
|
+
- `todosStatus` {number} - the HTTP status code from the most recent response for that resource (one per resource as `${resourceKey}Status`)
|
|
260
262
|
- `hasLoaded` {boolean} - all critical resources have successfully completed and are ready to be used by the component
|
|
261
263
|
- `isLoading` {boolean} - any of the critical resources are still in the process of being fetched
|
|
262
264
|
- `hasErrored` {boolean} - any of the critical resource requests did not complete successfully
|
|
@@ -494,7 +496,7 @@ As alluded to in the [Other Props](#other-props-returned-from-the-hookpassed-fro
|
|
|
494
496
|
|
|
495
497
|
- De-prioritize fetching the resource until after all critical resources have been fetched
|
|
496
498
|
- Remove the resource from consideration within the component-wide loading states (`hasLoaded`, `isLoading`, `hasErrored`), giving us the ability to render without waiting on those resources
|
|
497
|
-
- Can set our own UI logic around displaying noncritical data based on their individual loading states, ie `usersLoadingState`, which can be passed to the pure helper methods, `Utils.hasLoaded`, `Utils.hasErrored`, and `Utils.
|
|
499
|
+
- Can set our own UI logic around displaying noncritical data based on their individual loading states, ie `usersLoadingState`, which can be passed to the pure helper methods, `Utils.hasLoaded`, `Utils.hasErrored`, `Utils.isLoading`, and `Utils.isPending` from `resourcerer`.
|
|
498
500
|
|
|
499
501
|
|
|
500
502
|
|
|
@@ -520,7 +522,7 @@ This behavior is similar to the behavior you get with [cache invalidation](#cach
|
|
|
520
522
|
Passing a `resourceKey: <ResourceKeys>` option allows you to pass a custom name as the `withResources` key, which will become the base name for component-related props passed down to the component. For example, this configuration:
|
|
521
523
|
|
|
522
524
|
```js
|
|
523
|
-
const getResources = (props) => ({myRadTodos: {resourceKey: todos});
|
|
525
|
+
const getResources = (props) => ({myRadTodos: {resourceKey: 'todos'}});
|
|
524
526
|
|
|
525
527
|
export default function MyComponentWithTodos {
|
|
526
528
|
const {
|
|
@@ -620,7 +622,7 @@ function TodoSearch(props) {
|
|
|
620
622
|
|
|
621
623
|
// todo_search_item.jsx
|
|
622
624
|
// the todoModel is never actually fetched here, it's only listened on, allowing any changes made elsewhere in the page to be reflected here.
|
|
623
|
-
getResources = () => ({todo: {id: props.id, lazy: true}});
|
|
625
|
+
getResources = () => ({todo: {data: {id: props.id, lazy: true}});
|
|
624
626
|
|
|
625
627
|
function TodoSearchItem(props) {
|
|
626
628
|
const {todoModel} = useResources(getResources, props);
|
|
@@ -637,7 +639,20 @@ If the todo model has been fetched already, we'll read straight from that. And i
|
|
|
637
639
|
|
|
638
640
|
### minDuration
|
|
639
641
|
|
|
640
|
-
Sometimes requests can be _too_ fast for certain UIs. In these cases, spinners and other loading states can appear more like a jarring flicker than a helpful status indicator. For these, you can pass a `minDuration` equal to the minimum number of milliseconds that a request should take
|
|
642
|
+
Sometimes requests can be _too_ fast for certain UIs. In these cases, spinners and other loading states can appear more like a jarring flicker than a helpful status indicator. For these, you can pass a `minDuration` equal to the minimum number of milliseconds that a request should take on [save and destroy](#data-mutations) calls (for example `model.save(attrs, {minDuration: 300})`). It is not a resource config option and is not applied to fetches made through `useResources` / `withResources`.
|
|
643
|
+
|
|
644
|
+
### fetch
|
|
645
|
+
|
|
646
|
+
Pass `fetch: false` (or any expression that evaluates to false) to instantiate and cache a model **without** calling the network. Useful when composing a new resource client-side before it has an id, or when you already have data. See [Unfetched Resources](/docs/advanced_topics.md#unfetched-resources) and [Recaching newly-saved models](/docs/advanced_topics.md#recaching-newly-saved-models).
|
|
647
|
+
|
|
648
|
+
```js
|
|
649
|
+
const getResources = (props) => ({
|
|
650
|
+
todo: {
|
|
651
|
+
data: {id: props.id},
|
|
652
|
+
fetch: !!props.id
|
|
653
|
+
}
|
|
654
|
+
});
|
|
655
|
+
```
|
|
641
656
|
|
|
642
657
|
### dependsOn
|
|
643
658
|
|
|
@@ -645,7 +660,7 @@ See the section on [serial requests](#serial-requests).
|
|
|
645
660
|
|
|
646
661
|
### provides
|
|
647
662
|
|
|
648
|
-
See the section on [serial requests](#serial-requests).
|
|
663
|
+
See the section on [serial requests](#serial-requests). The `provides` function receives `(model, props)` and should return a map of prop names to values that get set via `setResourceState` for dependent resources.
|
|
649
664
|
|
|
650
665
|
# Data Mutations
|
|
651
666
|
|
|
@@ -659,7 +674,7 @@ So far we've only discussed fetching data. But `resourcerer` also makes it very
|
|
|
659
674
|
function MyComponent(props) {
|
|
660
675
|
const {myModel} = useResources(getResources, props),
|
|
661
676
|
onSave = () => myModel.save({foo: 'bar'})
|
|
662
|
-
.then([model]) => // ...)
|
|
677
|
+
.then(([model]) => // ...)
|
|
663
678
|
.catch(() => alert('request failed'));
|
|
664
679
|
|
|
665
680
|
return <button onClick={onSave}>Persist model</button>;
|
|
@@ -1236,7 +1251,7 @@ ResourcesConfig.set(configObj);
|
|
|
1236
1251
|
|
|
1237
1252
|
* Can `resourcerer` do anything other than `GET` requests?
|
|
1238
1253
|
|
|
1239
|
-
`resourcerer` only handles resource _fetching_ (i.e. calling [Model.prototype.fetch](/docs/model.md#fetch))
|
|
1254
|
+
`resourcerer` only handles resource _fetching_ (i.e. calling [Model.prototype.fetch](/docs/model.md#fetch)), which defaults to `GET`. If a resource needs a different HTTP method (for example a search endpoint that takes a POST body), override [`fetch`](/docs/model.md#fetch) on that Model/Collection class once—do not set `method` in each resource config.
|
|
1240
1255
|
|
|
1241
1256
|
For write operations, use Models' [`save`](/docs/model.md#save) and [`destroy`](/docs/model.md#destroy) methods directly:
|
|
1242
1257
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import Events from "./events.js";
|
|
2
2
|
import Model from "./model.js";
|
|
3
|
+
import { type CollectionConstructor } from "./collection.js";
|
|
3
4
|
export default class CanonicalModel<T extends Record<string, any>> extends Events<[
|
|
4
5
|
Partial<T>,
|
|
5
6
|
Model
|
|
@@ -9,6 +10,7 @@ export default class CanonicalModel<T extends Record<string, any>> extends Event
|
|
|
9
10
|
set(attrs: Partial<T> | undefined, context: Model, options?: {
|
|
10
11
|
unset?: boolean;
|
|
11
12
|
}): void;
|
|
13
|
+
removeSubscribersFromCollection(CollectionClass: CollectionConstructor, source: Model<any, any>): void;
|
|
12
14
|
removeSubscription(context: Model<any, any>, id: string | number): void;
|
|
13
15
|
toJSON(): T;
|
|
14
16
|
}
|
|
@@ -20,6 +20,16 @@ export default class CanonicalModel extends Events {
|
|
|
20
20
|
this.triggerUpdate(this.toJSON(), context);
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
|
+
removeSubscribersFromCollection(CollectionClass, source) {
|
|
24
|
+
for (const { context } of this._callbacks) {
|
|
25
|
+
const model = context;
|
|
26
|
+
if (model !== source &&
|
|
27
|
+
model.collection &&
|
|
28
|
+
model.collection.constructor === CollectionClass) {
|
|
29
|
+
model.collection.remove(model);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
23
33
|
removeSubscription(context, id) {
|
|
24
34
|
this.offUpdate(context);
|
|
25
35
|
if (!this._callbacks.length) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import Events from "./events.js";
|
|
2
2
|
import Model, { type CanonicalModelSubscription, type ConstructorOptions, type SetOptions } from "./model.js";
|
|
3
3
|
import sync, { type SyncOptions } from "./sync.js";
|
|
4
|
-
import { ResourceConfigObj } from "./types.js";
|
|
4
|
+
import { ResourceConfigObj, ResourceKeys } from "./types.js";
|
|
5
5
|
import CanonicalModelConstructor from "./canonical-model.js";
|
|
6
6
|
type CSetOptions = {
|
|
7
7
|
parse?: boolean;
|
|
@@ -33,7 +33,7 @@ export default class Collection<T extends Record<string, any> = object, O extend
|
|
|
33
33
|
static cacheTimeout: number;
|
|
34
34
|
static comparator: comparator;
|
|
35
35
|
static measure: boolean | ((config: ResourceConfigObj) => boolean);
|
|
36
|
-
|
|
36
|
+
static invalidates: ResourceKeys[];
|
|
37
37
|
toJSON(): T[];
|
|
38
38
|
sync(...args: Parameters<typeof sync>): Promise<[any, Response]>;
|
|
39
39
|
add(models: ModelArg<T, O> | ModelArg<T, O>[], options?: CSetOptions): this;
|
|
@@ -44,6 +44,7 @@ export default class Collection<T extends Record<string, any> = object, O extend
|
|
|
44
44
|
has(obj: Model<T, O>["id"] | ModelArg<T, O>): boolean;
|
|
45
45
|
at(index: number): InstanceType<this["Model"]> | undefined;
|
|
46
46
|
map(predicate: (model: InstanceType<this["Model"]>) => any): any[];
|
|
47
|
+
forEach(predicate: (model: InstanceType<this["Model"]>) => void): void;
|
|
47
48
|
find(predicate: (model: InstanceType<this["Model"]>) => boolean): InstanceType<M> | undefined;
|
|
48
49
|
filter(predicate: (model: InstanceType<this["Model"]>) => boolean): InstanceType<M>[];
|
|
49
50
|
findWhere(attrs: Partial<T>): InstanceType<this["Model"]> | undefined;
|
|
@@ -66,4 +67,5 @@ export default class Collection<T extends Record<string, any> = object, O extend
|
|
|
66
67
|
_removeReference(model: Model<T, O>): void;
|
|
67
68
|
_updateModelReference(id: string | number, prevId: string | number, model: InstanceType<M>): void;
|
|
68
69
|
}
|
|
70
|
+
export type CollectionConstructor = abstract new (...args: any[]) => Collection;
|
|
69
71
|
export {};
|
package/build/lib/collection.js
CHANGED
|
@@ -32,6 +32,7 @@ export default class Collection extends Events {
|
|
|
32
32
|
static cacheTimeout;
|
|
33
33
|
static comparator;
|
|
34
34
|
static measure = false;
|
|
35
|
+
static invalidates = [];
|
|
35
36
|
toJSON() {
|
|
36
37
|
return this.map((model) => model.toJSON());
|
|
37
38
|
}
|
|
@@ -109,6 +110,9 @@ export default class Collection extends Events {
|
|
|
109
110
|
map(predicate) {
|
|
110
111
|
return this.models.map(predicate);
|
|
111
112
|
}
|
|
113
|
+
forEach(predicate) {
|
|
114
|
+
this.models.forEach(predicate);
|
|
115
|
+
}
|
|
112
116
|
find(predicate) {
|
|
113
117
|
return this.models.find(predicate);
|
|
114
118
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import Collection from "./collection.js";
|
|
2
|
-
import Model from "./model.js";
|
|
1
|
+
import type Collection from "./collection.js";
|
|
2
|
+
import type Model from "./model.js";
|
|
3
3
|
import { ResourceKeys } from "./types.js";
|
|
4
4
|
type Component = NonNullable<unknown>;
|
|
5
5
|
declare const ModelCache: {
|
|
@@ -12,6 +12,7 @@ declare const ModelCache: {
|
|
|
12
12
|
measure: boolean | ((config: import("./types.js").ResourceConfigObj) => boolean);
|
|
13
13
|
subscriptions: import("./model.js").CanonicalModelSubscription[];
|
|
14
14
|
CanonicalModel: (new (...args: any[]) => import("./canonical-model.js").default<any>) | null;
|
|
15
|
+
invalidates: ResourceKeys[];
|
|
15
16
|
}> | undefined;
|
|
16
17
|
put(cacheKey: string, model: Model | Collection, component?: Component): void;
|
|
17
18
|
register(cacheKey: string, component?: Component): void;
|
package/build/lib/model.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import Events from "./events.js";
|
|
2
2
|
import sync, { type SyncOptions } from "./sync.js";
|
|
3
|
-
import Collection from "./collection.js";
|
|
4
|
-
import { NestedKeys, ResourceConfigObj } from "./types.js";
|
|
3
|
+
import Collection, { type CollectionConstructor } from "./collection.js";
|
|
4
|
+
import { NestedKeys, ResourceConfigObj, ResourceKeys } from "./types.js";
|
|
5
5
|
import CanonicalModel from "./canonical-model.js";
|
|
6
6
|
export type ConstructorOptions = {
|
|
7
7
|
collection?: Collection;
|
|
@@ -37,6 +37,7 @@ export default class Model<T extends Record<string, any> = Record<string, any>,
|
|
|
37
37
|
static measure: boolean | ((config: ResourceConfigObj) => boolean);
|
|
38
38
|
static subscriptions: CanonicalModelSubscription[];
|
|
39
39
|
static CanonicalModel: (new (...args: any[]) => CanonicalModel<any>) | null;
|
|
40
|
+
static invalidates: ResourceKeys[];
|
|
40
41
|
toJSON(): T;
|
|
41
42
|
sync(...args: Parameters<typeof sync>): Promise<[any, Response]>;
|
|
42
43
|
get<K extends keyof T>(attr: K): T[K];
|
|
@@ -58,7 +59,9 @@ export default class Model<T extends Record<string, any> = Record<string, any>,
|
|
|
58
59
|
isNew(): boolean;
|
|
59
60
|
_subscribe(attrs?: Partial<T>): void;
|
|
60
61
|
unsubscribe(): void;
|
|
62
|
+
_removePeerSubscribers(CollectionClass?: CollectionConstructor): void;
|
|
61
63
|
_updateSubscriptions(attrs?: Partial<T>, options?: SetOptions): void;
|
|
64
|
+
_invalidateRelated(): void;
|
|
62
65
|
_getSubscriptions(): (CanonicalModelSubscription<Record<string, any>, Record<string, any>> | {
|
|
63
66
|
Model: new (...args: any[]) => CanonicalModel<any>;
|
|
64
67
|
idField: string;
|
package/build/lib/model.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getNestedValue, isDeepEqual, result, uniqueId, urlError } from "./utils.js";
|
|
2
2
|
import Events from "./events.js";
|
|
3
3
|
import sync from "./sync.js";
|
|
4
|
+
import { invalidate } from "./model-cache.js";
|
|
4
5
|
import CanonicalModelCache from "./canonical-model-cache.js";
|
|
5
6
|
const RESERVED_OPTION_KEYS = [
|
|
6
7
|
"Model",
|
|
@@ -45,6 +46,7 @@ export default class Model extends Events {
|
|
|
45
46
|
static measure = false;
|
|
46
47
|
static subscriptions = [];
|
|
47
48
|
static CanonicalModel = null;
|
|
49
|
+
static invalidates = [];
|
|
48
50
|
toJSON() {
|
|
49
51
|
return { ...this.attributes };
|
|
50
52
|
}
|
|
@@ -131,6 +133,7 @@ export default class Model extends Events {
|
|
|
131
133
|
this._subscribe(serverAttrs);
|
|
132
134
|
this.set(serverAttrs, { silent: true, ...options });
|
|
133
135
|
this.triggerUpdate();
|
|
136
|
+
this._invalidateRelated();
|
|
134
137
|
return [this, response];
|
|
135
138
|
})
|
|
136
139
|
.catch((response) => {
|
|
@@ -147,6 +150,7 @@ export default class Model extends Events {
|
|
|
147
150
|
const request = this.isNew() ?
|
|
148
151
|
Promise.resolve([])
|
|
149
152
|
: this.sync(this, { method: "DELETE", ...options }), collection = this.collection;
|
|
153
|
+
const CollectionClass = collection?.constructor;
|
|
150
154
|
if (!options.wait) {
|
|
151
155
|
this.triggerUpdate();
|
|
152
156
|
this.collection?.remove(this, { silent: true });
|
|
@@ -157,7 +161,11 @@ export default class Model extends Events {
|
|
|
157
161
|
this.triggerUpdate();
|
|
158
162
|
this.collection?.remove(this, { silent: true });
|
|
159
163
|
}
|
|
164
|
+
if (!this.isNew()) {
|
|
165
|
+
this._removePeerSubscribers(CollectionClass);
|
|
166
|
+
}
|
|
160
167
|
this.unsubscribe();
|
|
168
|
+
this._invalidateRelated();
|
|
161
169
|
return [this, response];
|
|
162
170
|
})
|
|
163
171
|
.catch((response) => {
|
|
@@ -213,6 +221,23 @@ export default class Model extends Events {
|
|
|
213
221
|
}
|
|
214
222
|
}
|
|
215
223
|
}
|
|
224
|
+
_removePeerSubscribers(CollectionClass) {
|
|
225
|
+
if (!CollectionClass) {
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
const subscriptions = this._getSubscriptions();
|
|
229
|
+
const idAttribute = this.constructor.idAttribute;
|
|
230
|
+
for (const { Model: CanonicalModel, idField = idAttribute } of subscriptions) {
|
|
231
|
+
if (idField !== idAttribute) {
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
const id = getNestedValue(this.toJSON(), idField);
|
|
235
|
+
if (id && !this.isEmptyModel) {
|
|
236
|
+
const canonicalModel = CanonicalModelCache.getOrInsert(CanonicalModel, id);
|
|
237
|
+
canonicalModel.removeSubscribersFromCollection(CollectionClass, this);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
216
241
|
_updateSubscriptions(attrs = {}, options = {}) {
|
|
217
242
|
const subscriptions = this._getSubscriptions();
|
|
218
243
|
const idAttribute = this.constructor.idAttribute;
|
|
@@ -224,6 +249,15 @@ export default class Model extends Events {
|
|
|
224
249
|
}
|
|
225
250
|
}
|
|
226
251
|
}
|
|
252
|
+
_invalidateRelated() {
|
|
253
|
+
const keys = [
|
|
254
|
+
...this.constructor.invalidates,
|
|
255
|
+
...(this.collection?.constructor?.invalidates ?? []),
|
|
256
|
+
];
|
|
257
|
+
if (keys.length) {
|
|
258
|
+
window.setTimeout(() => invalidate(keys), 0);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
227
261
|
_getSubscriptions() {
|
|
228
262
|
const { subscriptions, idAttribute, CanonicalModel } = this.constructor;
|
|
229
263
|
return [
|
package/build/lib/request.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ export declare const getFromCache: (key: string) => Model<Record<string, any>, R
|
|
|
19
19
|
measure: boolean | ((config: import("./types.js").ResourceConfigObj) => boolean);
|
|
20
20
|
subscriptions: import("./model.js").CanonicalModelSubscription[];
|
|
21
21
|
CanonicalModel: (new (...args: any[]) => import("./canonical-model.js").default<any>) | null;
|
|
22
|
+
invalidates: import("./types.js").ResourceKeys[];
|
|
22
23
|
}> | undefined;
|
|
23
24
|
export declare const existsInCache: (key: string) => boolean;
|
|
24
25
|
declare const _default: (key: string, Model: {
|
package/build/lib/types.d.ts
CHANGED
|
@@ -18,6 +18,7 @@ export type ResourceConfigObj = {
|
|
|
18
18
|
[key: string]: any;
|
|
19
19
|
};
|
|
20
20
|
dependsOn?: boolean;
|
|
21
|
+
fetch?: boolean;
|
|
21
22
|
force?: boolean;
|
|
22
23
|
lazy?: boolean;
|
|
23
24
|
resourceKey?: ResourceKeys;
|
|
@@ -55,7 +56,7 @@ export type UseResourcesResponse = {
|
|
|
55
56
|
hasErrored: boolean;
|
|
56
57
|
hasLoaded: boolean;
|
|
57
58
|
hasInitiallyLoaded: boolean;
|
|
58
|
-
refetch: (keys: ResourceKeys[]) => void;
|
|
59
|
+
refetch: (keys: ResourceKeys | ResourceKeys[]) => void;
|
|
59
60
|
invalidate: typeof invalidate;
|
|
60
61
|
setResourceState(newState: {
|
|
61
62
|
[key: string]: any;
|
package/docs/advanced_topics.md
CHANGED
|
@@ -55,8 +55,9 @@ Using `dependsOn` in simple cases like the one highlighted in the [README](https
|
|
|
55
55
|
|
|
56
56
|
// this assumes that the parent is handling the `hasErrored` state. if it is not, then
|
|
57
57
|
// you may need to instead use:
|
|
58
|
+
// import {Utils} from 'resourcerer';
|
|
58
59
|
shouldComponentUpdate(nextProps) {
|
|
59
|
-
return !(nextProps.isLoading ||
|
|
60
|
+
return !(nextProps.isLoading || Utils.isPending(nextProps.myDependentLoadingState));
|
|
60
61
|
}
|
|
61
62
|
```
|
|
62
63
|
|
|
@@ -116,7 +117,20 @@ In this case, when the component is used as an order component (denoted by the p
|
|
|
116
117
|
|
|
117
118
|
For all other uses of dependent resources, we should use `dependsOn`.
|
|
118
119
|
|
|
120
|
+
## Unfetched Resources
|
|
119
121
|
|
|
122
|
+
Sometimes you want a Model instance in the cache _without_ hitting the network—for example, while composing a new resource in a form before it has an id. Pass `fetch: false` (or a boolean expression that evaluates to false) in the resource config:
|
|
123
|
+
|
|
124
|
+
```js
|
|
125
|
+
const getResources = (props) => ({
|
|
126
|
+
todo: {
|
|
127
|
+
data: {id: props.id},
|
|
128
|
+
fetch: !!props.id
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
When `fetch` is false, resourcerer still constructs and caches the model (initialized from `data`) and returns it to your component, but it does not call `model.fetch()`. See [Recaching newly-saved models](#recaching-newly-saved-models) for the common create-then-navigate pattern that builds on this.
|
|
120
134
|
|
|
121
135
|
## Loading Overlays
|
|
122
136
|
|
package/docs/collection.md
CHANGED
|
@@ -51,6 +51,15 @@ The number of milliseconds to keep all collections of this class in the cache af
|
|
|
51
51
|
|
|
52
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
53
|
|
|
54
|
+
### `static` invalidates
|
|
55
|
+
`ResourceKeys[]`
|
|
56
|
+
|
|
57
|
+
Same as [Model `static invalidates`](/docs/model.md#static-invalidates): resource keys to remove from the cache after a successful write that goes through this collection's shared save/destroy invalidation path. Prefer declarative invalidation when related resources should clear together; use imperative [`invalidate`](https://github.com/noahgrant/resourcerer#cache-invalidation) for one-off cases.
|
|
58
|
+
|
|
59
|
+
### `static` subscriptions / `static` CanonicalModel
|
|
60
|
+
|
|
61
|
+
For keeping denormalized fields in sync across models, see [Canonical Models](https://github.com/noahgrant/resourcerer#canonical-models).
|
|
62
|
+
|
|
54
63
|
### `static` idAttribute
|
|
55
64
|
|
|
56
65
|
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:
|
|
@@ -70,7 +79,7 @@ static idAttribute = 'name'
|
|
|
70
79
|
constructor: (models: Array<Record<string, any> | Model>, options: object) => void
|
|
71
80
|
```
|
|
72
81
|
|
|
73
|
-
The Collection's constructor gets passed any initial models, as well as the [
|
|
82
|
+
The Collection's constructor gets passed any initial models, as well as the [`path`](https://github.com/noahgrant/resourcerer#path) fields 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
83
|
|
|
75
84
|
```js
|
|
76
85
|
class MyCollection extends Collection<ModelType> {
|
|
@@ -87,7 +96,7 @@ class MyCollection extends Collection<ModelType> {
|
|
|
87
96
|
}
|
|
88
97
|
```
|
|
89
98
|
|
|
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 `path`
|
|
99
|
+
Passing in a `Model` option or a `comparator` option to an instance's constructor will override the statically defined properties on its constructor. Other [`path`](https://github.com/noahgrant/resourcerer#path) fields from the executor function are passed to the `url` as shown in the example above.
|
|
91
100
|
|
|
92
101
|
|
|
93
102
|
### add
|
|
@@ -95,14 +104,14 @@ Passing in a `Model` option or a `comparator` option to an instance's constructo
|
|
|
95
104
|
add: (models: Record<string, any> | Model | Array<Record<string, any> | Model>, options: Object) => this
|
|
96
105
|
```
|
|
97
106
|
|
|
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 `
|
|
107
|
+
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 `silent: 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
108
|
|
|
100
109
|
### create
|
|
101
110
|
```js
|
|
102
111
|
create: (model: Record<string, any> | Model, options: Object) => Promise<[Model, Response]>
|
|
103
112
|
```
|
|
104
113
|
|
|
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 [
|
|
114
|
+
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 [`path`](https://github.com/noahgrant/resourcerer#path) fields 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
115
|
|
|
107
116
|
***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
117
|
|
|
@@ -121,7 +130,7 @@ This is the method that `resourcerer` uses internally to get server data and set
|
|
|
121
130
|
get: (identifier: string | number) => Model | undefined
|
|
122
131
|
```
|
|
123
132
|
|
|
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 [`
|
|
133
|
+
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 [`idAttribute`](#static-idattribute) property. The `.get()` method takes an id value and returns the quick-lookup model instance if one exists.
|
|
125
134
|
|
|
126
135
|
### has
|
|
127
136
|
```js
|
|
@@ -224,6 +233,13 @@ map: (predicate: (Model) => any) => any[]
|
|
|
224
233
|
|
|
225
234
|
Same signature as Array.prototype.map across a collection's models.
|
|
226
235
|
|
|
236
|
+
### forEach
|
|
237
|
+
```js
|
|
238
|
+
forEach: (predicate: (Model) => void) => void
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Same signature as Array.prototype.forEach across a collection's models.
|
|
242
|
+
|
|
227
243
|
### pluck
|
|
228
244
|
```js
|
|
229
245
|
pluck: (attribute: string) => any[]
|
package/docs/migrating_to_2.0.md
CHANGED
|
@@ -35,14 +35,16 @@ The core methodology and functionality of `resourcerer` has not changed in versi
|
|
|
35
35
|
|
|
36
36
|
1. The utility methods `haveAllLoaded`, `areAnyLoading`, and `haveAnyErrored` have been placed under a top-level `Utils` object and are now named `Utils.hasLoaded`, `Utils.isLoading`, and `Utils.hasErrored`, resepectively, to provide consistency with other loading state names. Their signatures have not changed.
|
|
37
37
|
|
|
38
|
-
1. The [refetch](/#refetching) method returned from `useResources` no longer accepts a function as an argument. Pass an array of resource keys directly instead:
|
|
38
|
+
1. The [refetch](/#refetching) method returned from `useResources` no longer accepts a function as an argument. Pass a resource key or an array of resource keys directly instead:
|
|
39
39
|
|
|
40
40
|
```js
|
|
41
41
|
// previously
|
|
42
42
|
refetch(({todos}) => [todos]);
|
|
43
43
|
|
|
44
44
|
// now
|
|
45
|
-
refetch(
|
|
45
|
+
refetch("todos");
|
|
46
|
+
// or
|
|
47
|
+
refetch(["todos"]);
|
|
46
48
|
```
|
|
47
49
|
|
|
48
50
|
1. [dependsOn](/#serial-requests) is no longer an array of strings that checks existence of prop fields. To be more versatile, it is a boolean, and will fetch the resource whenever its conditions evaluate to true:
|
package/docs/model.md
CHANGED
|
@@ -65,7 +65,14 @@ An object or function that returns object with attribute keys and their default
|
|
|
65
65
|
|
|
66
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
67
|
|
|
68
|
+
### `static` invalidates
|
|
69
|
+
`ResourceKeys[]`
|
|
68
70
|
|
|
71
|
+
List of resource keys whose cache entries should be removed after a successful [`save`](#save) or [`destroy`](#destroy) on this model. Prefer this for declarative invalidation of related resources; use the imperative [`invalidate`](https://github.com/noahgrant/resourcerer#cache-invalidation) helper when you need one-off control from a component.
|
|
72
|
+
|
|
73
|
+
### `static` subscriptions / `static` CanonicalModel
|
|
74
|
+
|
|
75
|
+
For keeping denormalized fields in sync across models, see [Canonical Models](https://github.com/noahgrant/resourcerer#canonical-models).
|
|
69
76
|
|
|
70
77
|
## Methods
|
|
71
78
|
|
|
@@ -75,7 +82,7 @@ A boolean or function that accepts a [resource configuration object](https://git
|
|
|
75
82
|
constructor: (initialData: object, options: object) => void
|
|
76
83
|
```
|
|
77
84
|
|
|
78
|
-
The Model's constructor gets passed any initial data, as well as the [
|
|
85
|
+
The Model's constructor gets passed any initial data, as well as the [`path`](https://github.com/noahgrant/resourcerer#path) fields 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
86
|
|
|
80
87
|
```ts
|
|
81
88
|
class MyModel extends Model<ModelType> {
|
|
@@ -91,7 +98,7 @@ class MyModel extends Model<ModelType> {
|
|
|
91
98
|
}
|
|
92
99
|
```
|
|
93
100
|
|
|
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 [
|
|
101
|
+
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 [`path`](https://github.com/noahgrant/resourcerer#path) fields from the executor function are passed to the `url` as shown in the example above.
|
|
95
102
|
|
|
96
103
|
|
|
97
104
|
### toJSON
|
|
@@ -198,6 +205,20 @@ Use this to remove the send a DELETE request at this model's url to the server.
|
|
|
198
205
|
fetch: (options: Object) => Promise<[Model, Response]>
|
|
199
206
|
```
|
|
200
207
|
|
|
201
|
-
This is the method that `resourcerer` uses internally to get server data and set its parsed response as
|
|
208
|
+
This is the method that `resourcerer` uses internally to get server data and set its parsed response as attributes on the model. This should rarely need to be used in your application. Subscribed components will update when the request returns. Defaults to `GET`; override this method on a Model/Collection subclass when every fetch for that resource should use a different HTTP verb. `useResources` / `withResources` only forward `params` into this call.
|
|
202
209
|
|
|
203
210
|
***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.***
|
|
211
|
+
|
|
212
|
+
### sync
|
|
213
|
+
```js
|
|
214
|
+
sync: (model: Model | Collection, options: SyncOptions) => Promise<[any, Response]>
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Low-level networking used by [`fetch`](#fetch), [`save`](#save), and [`destroy`](#destroy). By default this is the package [`sync`](https://github.com/noahgrant/resourcerer/blob/main/lib/sync.ts) / `ajax` helpers (Fetch API under the hood). Override `Model.sync` (or `Collection.sync`) on a class or instance when you need custom transport. Common `SyncOptions` include:
|
|
218
|
+
|
|
219
|
+
* `method` — HTTP method (`GET` / `POST` / `PUT` / `PATCH` / `DELETE`)
|
|
220
|
+
* `params` — query string (GET) or JSON body (write methods)
|
|
221
|
+
* `minDuration` — minimum request duration in milliseconds (useful on `save` / `destroy`; not forwarded by resourcerer resource configs)
|
|
222
|
+
* `headers`, `url`, `attrs`, and anything else your [`prefilter`](https://github.com/noahgrant/resourcerer#configuring-resourcerer) / custom sync layer understands
|
|
223
|
+
|
|
224
|
+
Auth headers and global error handling belong in [`ResourcesConfig.prefilter`](https://github.com/noahgrant/resourcerer#configuring-resourcerer).
|
|
@@ -24,19 +24,20 @@ it('runs a test', () => {
|
|
|
24
24
|
|
|
25
25
|
### Changing resource loading states
|
|
26
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 [
|
|
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 [Vitest](https://vitest.dev/) or [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
28
|
|
|
29
29
|
```jsx
|
|
30
30
|
import * as resourcerer from 'resourcerer';
|
|
31
31
|
import {render} from '@testing-library/react';
|
|
32
|
+
import {vi} from 'vitest'; // or use jest.spyOn with Jest
|
|
32
33
|
|
|
33
34
|
// ...
|
|
34
35
|
it('shows a loader when in a loading state', () => {
|
|
35
|
-
|
|
36
|
+
vi.spyOn(resourcerer, 'useResources').mockImplementation((fn, props) => ({
|
|
36
37
|
...props,
|
|
37
38
|
hasLoaded: false,
|
|
38
39
|
isLoading: true
|
|
39
|
-
));
|
|
40
|
+
}));
|
|
40
41
|
|
|
41
42
|
const {container} = render(<MyComponent />);
|
|
42
43
|
|
|
@@ -47,12 +48,12 @@ it('shows a loader when in a loading state', () => {
|
|
|
47
48
|
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
|
|
|
49
50
|
```jsx
|
|
50
|
-
var setResourceMock =
|
|
51
|
+
var setResourceMock = vi.fn();
|
|
51
52
|
|
|
52
|
-
|
|
53
|
+
vi.spyOn(resourcerer, 'useResources').mockImplementation((fn, props) => ({
|
|
53
54
|
...props,
|
|
54
55
|
setResourceState: setResourceMock
|
|
55
|
-
));
|
|
56
|
+
}));
|
|
56
57
|
```
|
|
57
58
|
|
|
58
59
|
Keep in mind that in this case the calls to `setResourceState` won't actually go through, and so state won't persist.
|
package/docs/typescript.md
CHANGED
|
@@ -41,7 +41,7 @@ interface Todo {
|
|
|
41
41
|
name: string;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
-
export default TodosCollection extends Collection<Todo> {
|
|
44
|
+
export default class TodosCollection extends Collection<Todo> {
|
|
45
45
|
url({userId}: {userId: string}) {
|
|
46
46
|
return `/${userId}/todos`;
|
|
47
47
|
}
|
|
@@ -98,7 +98,7 @@ function MyComponent(props) {
|
|
|
98
98
|
} = useResources(({userId}) => ({todos: {params: {userId}}}), {ursdI: "oops"});
|
|
99
99
|
```
|
|
100
100
|
|
|
101
|
-
But inlining executor functions leaves you susceptible to [the subtle bug where you are always reading from current props](https://github.com/noahgrant/resourcerer
|
|
101
|
+
But inlining executor functions leaves you susceptible to [the subtle bug where you are always reading from current props](https://github.com/noahgrant/resourcerer#differences-between-useresources-and-withresources). Executor functions can also get pretty involved, so it's nice to extract it. You still get good type hints, but you'll need to type out your props:
|
|
102
102
|
|
|
103
103
|
```tsx
|
|
104
104
|
// type out these props
|
package/package.json
CHANGED
package/resourcerer.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ declare module "resourcerer" {
|
|
|
16
16
|
export type ResourceConfigObj<K extends ResourceKeys> = {
|
|
17
17
|
data?: Partial<GetModelOptions<InstanceType<ModelMap[K]>>[0]>;
|
|
18
18
|
dependsOn?: boolean;
|
|
19
|
+
fetch?: boolean;
|
|
19
20
|
force?: boolean;
|
|
20
21
|
lazy?: boolean;
|
|
21
22
|
noncritical?: boolean;
|
|
@@ -29,6 +30,7 @@ declare module "resourcerer" {
|
|
|
29
30
|
model: InstanceType<ModelMap[K]>,
|
|
30
31
|
props: Record<string, any>
|
|
31
32
|
) => { [key: string]: any };
|
|
33
|
+
resourceKey?: ResourceKeys;
|
|
32
34
|
};
|
|
33
35
|
|
|
34
36
|
export interface ModelMap {}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import CanonicalModelCache from "../lib/canonical-model-cache";
|
|
1
|
+
import CanonicalModelCache, { canonicalModelCache } from "../lib/canonical-model-cache";
|
|
2
|
+
import Collection from "../lib/collection";
|
|
2
3
|
import Model from "../lib/model";
|
|
3
4
|
import { vi } from "vitest";
|
|
4
5
|
import CanonicalModel from "../lib/canonical-model";
|
|
@@ -12,6 +13,7 @@ describe("CanonicalModel", () => {
|
|
|
12
13
|
|
|
13
14
|
afterEach(() => {
|
|
14
15
|
callback.mockClear();
|
|
16
|
+
canonicalModelCache.clear();
|
|
15
17
|
});
|
|
16
18
|
|
|
17
19
|
describe("get", () => {
|
|
@@ -51,6 +53,43 @@ describe("CanonicalModel", () => {
|
|
|
51
53
|
});
|
|
52
54
|
});
|
|
53
55
|
|
|
56
|
+
describe("removeSubscribersFromCollection", () => {
|
|
57
|
+
class UsersCollection extends Collection {
|
|
58
|
+
static CanonicalModel = CanonicalTestModel;
|
|
59
|
+
|
|
60
|
+
url() {
|
|
61
|
+
return "/users";
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
class UserDetailsCollection extends Collection {
|
|
66
|
+
static CanonicalModel = CanonicalTestModel;
|
|
67
|
+
|
|
68
|
+
url() {
|
|
69
|
+
return "/user-details";
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
it("removes peer models from the same collection class but not other collection classes", () => {
|
|
74
|
+
const canonicalModel = new CanonicalTestModel();
|
|
75
|
+
const activeUsers = new UsersCollection([{ id: "1234" }]);
|
|
76
|
+
const allUsers = new UsersCollection([{ id: "1234" }]);
|
|
77
|
+
const userDetails = new UserDetailsCollection([{ id: "1234" }]);
|
|
78
|
+
const source = activeUsers.get("1234");
|
|
79
|
+
|
|
80
|
+
canonicalModel.onUpdate(() => {}, activeUsers.get("1234"));
|
|
81
|
+
canonicalModel.onUpdate(() => {}, allUsers.get("1234"));
|
|
82
|
+
canonicalModel.onUpdate(() => {}, userDetails.get("1234"));
|
|
83
|
+
|
|
84
|
+
canonicalModel.removeSubscribersFromCollection(UsersCollection, source);
|
|
85
|
+
|
|
86
|
+
// we didn't actually remove it from this collection, it's jus the source
|
|
87
|
+
expect(activeUsers.has("1234")).toBe(true);
|
|
88
|
+
expect(allUsers.has("1234")).toBe(false);
|
|
89
|
+
expect(userDetails.has("1234")).toBe(true);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
|
|
54
93
|
describe("removeSubscription", () => {
|
|
55
94
|
const subscriberModel = new Model();
|
|
56
95
|
|
package/test/collection.test.js
CHANGED
|
@@ -411,6 +411,17 @@ describe("Collection", () => {
|
|
|
411
411
|
});
|
|
412
412
|
});
|
|
413
413
|
|
|
414
|
+
describe("forEach", () => {
|
|
415
|
+
it("runs a forEach function across the models", () => {
|
|
416
|
+
collection.forEach((model, i) => model.set({ index: i }));
|
|
417
|
+
expect(collection.toJSON()).toEqual([
|
|
418
|
+
{ id: "model1", index: 0 },
|
|
419
|
+
{ id: "model2", index: 1 },
|
|
420
|
+
{ id: "model3", index: 2 },
|
|
421
|
+
]);
|
|
422
|
+
});
|
|
423
|
+
});
|
|
424
|
+
|
|
414
425
|
describe("find", () => {
|
|
415
426
|
it("finds the first model that passes the predicate", () => {
|
|
416
427
|
expect(collection.find((model, i) => i === 1)).toEqual(model2);
|
package/test/model.test.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as sync from "../lib/sync";
|
|
2
|
+
import * as modelCache from "../lib/model-cache";
|
|
2
3
|
import CanonicalModel from "../lib/canonical-model";
|
|
3
4
|
import { canonicalModelCache } from "../lib/canonical-model-cache";
|
|
4
5
|
|
|
@@ -454,6 +455,180 @@ describe("Model", () => {
|
|
|
454
455
|
expect(err).toEqual(response);
|
|
455
456
|
}
|
|
456
457
|
});
|
|
458
|
+
|
|
459
|
+
describe("peer collections", () => {
|
|
460
|
+
class CanonicalUserModel extends CanonicalModel {}
|
|
461
|
+
|
|
462
|
+
class UsersCollection extends Collection {
|
|
463
|
+
static CanonicalModel = CanonicalUserModel;
|
|
464
|
+
|
|
465
|
+
url() {
|
|
466
|
+
return "/users";
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
class UserDetailsCollection extends Collection {
|
|
471
|
+
static CanonicalModel = CanonicalUserModel;
|
|
472
|
+
|
|
473
|
+
url() {
|
|
474
|
+
return "/user-details";
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
afterEach(() => {
|
|
479
|
+
canonicalModelCache.clear();
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
it("removes the model from other instances of the same collection class after DELETE succeeds", async () => {
|
|
483
|
+
const activeUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
|
|
484
|
+
const allUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
|
|
485
|
+
const userDetails = new UserDetailsCollection([{ id: "1234", name: "Bob" }]);
|
|
486
|
+
|
|
487
|
+
await activeUsers.get("1234").destroy();
|
|
488
|
+
|
|
489
|
+
expect(activeUsers.has("1234")).toBe(false);
|
|
490
|
+
expect(allUsers.has("1234")).toBe(false);
|
|
491
|
+
expect(userDetails.has("1234")).toBe(true);
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
it("removes peers only after the request resolves when `wait` is true", async () => {
|
|
495
|
+
const activeUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
|
|
496
|
+
const allUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
|
|
497
|
+
|
|
498
|
+
model = activeUsers.get("1234");
|
|
499
|
+
const request = model.destroy({ wait: true });
|
|
500
|
+
|
|
501
|
+
expect(allUsers.has("1234")).toBe(true);
|
|
502
|
+
await request;
|
|
503
|
+
expect(allUsers.has("1234")).toBe(false);
|
|
504
|
+
});
|
|
505
|
+
|
|
506
|
+
it("does not remove peers when the request rejects", async () => {
|
|
507
|
+
sync.default.mockRejectedValue(response);
|
|
508
|
+
|
|
509
|
+
const activeUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
|
|
510
|
+
const allUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
|
|
511
|
+
|
|
512
|
+
model = activeUsers.get("1234");
|
|
513
|
+
|
|
514
|
+
try {
|
|
515
|
+
await model.destroy();
|
|
516
|
+
} catch (err) {
|
|
517
|
+
expect(allUsers.has("1234")).toBe(true);
|
|
518
|
+
expect(err).toEqual(response);
|
|
519
|
+
}
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
it("removes peers when the canonical model is defined on the model subscriptions", async () => {
|
|
523
|
+
class User extends Model {
|
|
524
|
+
static subscriptions = [
|
|
525
|
+
{
|
|
526
|
+
Model: CanonicalUserModel,
|
|
527
|
+
toSource: (attrs) => attrs,
|
|
528
|
+
fromSource: (attrs) => attrs,
|
|
529
|
+
},
|
|
530
|
+
];
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
class SubscriptionsUsersCollection extends Collection {
|
|
534
|
+
static Model = User;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
const activeUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
|
|
538
|
+
const allUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
|
|
539
|
+
|
|
540
|
+
model = activeUsers.get("1234");
|
|
541
|
+
await model.destroy();
|
|
542
|
+
|
|
543
|
+
expect(allUsers.has("1234")).toBe(false);
|
|
544
|
+
});
|
|
545
|
+
|
|
546
|
+
it("does not remove peers when the canonical model id field and idAttribute are not equal", async () => {
|
|
547
|
+
class User extends Model {
|
|
548
|
+
static subscriptions = [
|
|
549
|
+
{
|
|
550
|
+
Model: CanonicalUserModel,
|
|
551
|
+
idField: "_id",
|
|
552
|
+
toSource: (attrs) => attrs,
|
|
553
|
+
fromSource: (attrs) => attrs,
|
|
554
|
+
},
|
|
555
|
+
];
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
class SubscriptionsUsersCollection extends Collection {
|
|
559
|
+
static Model = User;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const activeUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
|
|
563
|
+
const allUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
|
|
564
|
+
|
|
565
|
+
model = activeUsers.get("1234");
|
|
566
|
+
await model.destroy();
|
|
567
|
+
|
|
568
|
+
// canonical model subscription has an id field that does not equal idAttribute,
|
|
569
|
+
// so it is not removed
|
|
570
|
+
expect(allUsers.has("1234")).toBe(true);
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
it("removes peers when the canonical model id field and idAttribute are not the default 'id'", async () => {
|
|
574
|
+
class User extends Model {
|
|
575
|
+
static subscriptions = [
|
|
576
|
+
{
|
|
577
|
+
Model: CanonicalUserModel,
|
|
578
|
+
idField: "_id",
|
|
579
|
+
toSource: (attrs) => attrs,
|
|
580
|
+
fromSource: (attrs) => attrs,
|
|
581
|
+
},
|
|
582
|
+
];
|
|
583
|
+
|
|
584
|
+
static idAttribute = "_id";
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
class SubscriptionsUsersCollection extends Collection {
|
|
588
|
+
static Model = User;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
const activeUsers = new SubscriptionsUsersCollection([{ _id: "1234", name: "Bob" }]);
|
|
592
|
+
const allUsers = new SubscriptionsUsersCollection([{ _id: "1234", name: "Bob" }]);
|
|
593
|
+
|
|
594
|
+
model = activeUsers.get("1234");
|
|
595
|
+
await model.destroy();
|
|
596
|
+
|
|
597
|
+
expect(allUsers.has("1234")).toBe(false);
|
|
598
|
+
});
|
|
599
|
+
|
|
600
|
+
it("removes peers when the canonical model is defined on the collection", async () => {
|
|
601
|
+
class SubscriptionsUsersCollection extends Collection {
|
|
602
|
+
static CanonicalModel = CanonicalUserModel;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
const activeUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
|
|
606
|
+
const allUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
|
|
607
|
+
|
|
608
|
+
model = activeUsers.get("1234");
|
|
609
|
+
await model.destroy();
|
|
610
|
+
|
|
611
|
+
expect(allUsers.has("1234")).toBe(false);
|
|
612
|
+
});
|
|
613
|
+
|
|
614
|
+
it("removes peers when the canonical model is defined on the model class", async () => {
|
|
615
|
+
class User extends Model {
|
|
616
|
+
static CanonicalModel = CanonicalUserModel;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
class ModelUsersCollection extends Collection {
|
|
620
|
+
static Model = User;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
const activeUsers = new ModelUsersCollection([{ id: "1234", name: "Bob" }]);
|
|
624
|
+
const allUsers = new ModelUsersCollection([{ id: "1234", name: "Bob" }]);
|
|
625
|
+
|
|
626
|
+
model = activeUsers.get("1234");
|
|
627
|
+
await model.destroy();
|
|
628
|
+
|
|
629
|
+
expect(allUsers.has("1234")).toBe(false);
|
|
630
|
+
});
|
|
631
|
+
});
|
|
457
632
|
});
|
|
458
633
|
|
|
459
634
|
describe("url", () => {
|
|
@@ -982,6 +1157,126 @@ describe("Model", () => {
|
|
|
982
1157
|
]);
|
|
983
1158
|
});
|
|
984
1159
|
});
|
|
1160
|
+
|
|
1161
|
+
describe("invalidates", () => {
|
|
1162
|
+
beforeEach(() => {
|
|
1163
|
+
vi.useFakeTimers();
|
|
1164
|
+
vi.spyOn(modelCache, "invalidate");
|
|
1165
|
+
});
|
|
1166
|
+
|
|
1167
|
+
afterEach(() => {
|
|
1168
|
+
vi.useRealTimers();
|
|
1169
|
+
modelCache.invalidate.mockRestore();
|
|
1170
|
+
});
|
|
1171
|
+
|
|
1172
|
+
it("has an empty invalidates list by default", () => {
|
|
1173
|
+
expect(Model.invalidates).toEqual([]);
|
|
1174
|
+
});
|
|
1175
|
+
|
|
1176
|
+
it("does not call invalidate after save when invalidates is empty", async () => {
|
|
1177
|
+
model = new Model();
|
|
1178
|
+
await model.save();
|
|
1179
|
+
vi.runAllTimers();
|
|
1180
|
+
expect(modelCache.invalidate).not.toHaveBeenCalled();
|
|
1181
|
+
});
|
|
1182
|
+
|
|
1183
|
+
it("calls invalidate with the model's invalidates keys after a successful save", async () => {
|
|
1184
|
+
class _Model extends Model {
|
|
1185
|
+
static invalidates = ["todos", "user"];
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
model = new _Model();
|
|
1189
|
+
await model.save();
|
|
1190
|
+
expect(modelCache.invalidate).not.toHaveBeenCalled();
|
|
1191
|
+
|
|
1192
|
+
vi.runAllTimers();
|
|
1193
|
+
expect(modelCache.invalidate).toHaveBeenCalledWith(["todos", "user"]);
|
|
1194
|
+
});
|
|
1195
|
+
|
|
1196
|
+
it("calls invalidate with the model's invalidates keys after a successful destroy", async () => {
|
|
1197
|
+
class _Model extends Model {
|
|
1198
|
+
static invalidates = ["todos"];
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
model = new _Model({ id: "1234" });
|
|
1202
|
+
await model.destroy();
|
|
1203
|
+
expect(modelCache.invalidate).not.toHaveBeenCalled();
|
|
1204
|
+
|
|
1205
|
+
vi.runAllTimers();
|
|
1206
|
+
expect(modelCache.invalidate).toHaveBeenCalledWith(["todos"]);
|
|
1207
|
+
});
|
|
1208
|
+
|
|
1209
|
+
it("does not call invalidate after a failed save", async () => {
|
|
1210
|
+
class _Model extends Model {
|
|
1211
|
+
static invalidates = ["todos"];
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
sync.default.mockRejectedValue(new Error("failed"));
|
|
1215
|
+
model = new _Model();
|
|
1216
|
+
|
|
1217
|
+
try {
|
|
1218
|
+
await model.save();
|
|
1219
|
+
} catch (_) {
|
|
1220
|
+
// expected
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
vi.runAllTimers();
|
|
1224
|
+
expect(modelCache.invalidate).not.toHaveBeenCalled();
|
|
1225
|
+
});
|
|
1226
|
+
|
|
1227
|
+
it("does not call invalidate after a failed destroy", async () => {
|
|
1228
|
+
class _Model extends Model {
|
|
1229
|
+
static invalidates = ["todos"];
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
sync.default.mockRejectedValue(new Error("failed"));
|
|
1233
|
+
model = new _Model({ id: "1234" });
|
|
1234
|
+
|
|
1235
|
+
try {
|
|
1236
|
+
await model.destroy();
|
|
1237
|
+
} catch (_) {
|
|
1238
|
+
// expected
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
vi.runAllTimers();
|
|
1242
|
+
expect(modelCache.invalidate).not.toHaveBeenCalled();
|
|
1243
|
+
});
|
|
1244
|
+
|
|
1245
|
+
it("includes invalidates keys from the parent collection", async () => {
|
|
1246
|
+
class _Model extends Model {
|
|
1247
|
+
static invalidates = ["todos"];
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
class _Collection extends Collection {
|
|
1251
|
+
static invalidates = ["user"];
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
collection = new _Collection();
|
|
1255
|
+
model = new _Model({ id: "1234" }, { collection });
|
|
1256
|
+
await model.save();
|
|
1257
|
+
vi.runAllTimers();
|
|
1258
|
+
expect(modelCache.invalidate).toHaveBeenCalledWith(["todos", "user"]);
|
|
1259
|
+
});
|
|
1260
|
+
|
|
1261
|
+
it("defers invalidation so refetch can still find the model in the same .then() chain", async () => {
|
|
1262
|
+
class _Model extends Model {
|
|
1263
|
+
static invalidates = ["todos"];
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
model = new _Model();
|
|
1267
|
+
|
|
1268
|
+
let modelStillInCacheDuringSave = false;
|
|
1269
|
+
|
|
1270
|
+
await model.save().then(() => {
|
|
1271
|
+
modelStillInCacheDuringSave = true;
|
|
1272
|
+
expect(modelCache.invalidate).not.toHaveBeenCalled();
|
|
1273
|
+
});
|
|
1274
|
+
|
|
1275
|
+
expect(modelStillInCacheDuringSave).toBe(true);
|
|
1276
|
+
vi.runAllTimers();
|
|
1277
|
+
expect(modelCache.invalidate).toHaveBeenCalled();
|
|
1278
|
+
});
|
|
1279
|
+
});
|
|
985
1280
|
});
|
|
986
1281
|
|
|
987
1282
|
class CanonicalTestModel extends CanonicalModel {}
|