resourcerer 2.1.4 → 2.2.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 +131 -0
- package/build/lib/collection.d.ts +1 -0
- package/build/lib/model-cache.d.ts +2 -2
- package/build/lib/model.js +4 -2
- package/build/lib/request.d.ts +2 -2
- package/package.json +9 -7
- package/test/config.test.js +0 -1
- package/test/model.test.js +25 -8
- package/test/request.test.js +0 -2
package/README.md
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* prioritized rendering for critical data (enabling less critical or slower requests to not block interactivity)
|
|
9
9
|
* delayed requests
|
|
10
10
|
* prefetching
|
|
11
|
+
* inter-model syncing
|
|
11
12
|
* ...and more
|
|
12
13
|
|
|
13
14
|
Additional features include:
|
|
@@ -147,6 +148,7 @@ There's a lot there, so let's unpack that a bit. There's also a lot more that we
|
|
|
147
148
|
1. [provides](#provides)
|
|
148
149
|
1. [Data mutations](#data-mutations)
|
|
149
150
|
1. [Serial Requests](#serial-requests)
|
|
151
|
+
2. [Canonical Models](#canonical-models)
|
|
150
152
|
3. [Differences between useResources and withResources](#differences-between-useresources-and-withresources)
|
|
151
153
|
4. [Using resourcerer with TypeScript](docs/typescript.md)
|
|
152
154
|
4. [Caching Resources with ModelCache](#caching-resources-with-modelcache)
|
|
@@ -590,6 +592,8 @@ Like `params` and `path`, the `data` object will also be used in cache key gener
|
|
|
590
592
|
|
|
591
593
|
### lazy
|
|
592
594
|
|
|
595
|
+
##### (this feature is deprecated — use [canonical models](#canonical-models) instead.)
|
|
596
|
+
|
|
593
597
|
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.
|
|
594
598
|
|
|
595
599
|
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:
|
|
@@ -765,6 +769,133 @@ export default function QueueItemPage(props) {
|
|
|
765
769
|
}
|
|
766
770
|
```
|
|
767
771
|
|
|
772
|
+
## Canonical Models
|
|
773
|
+
|
|
774
|
+
Generally, we can't always be RESTful, all the time. Imagine this scenario: we want to show the name of who created a TODO item in our list of TODOS. If we were being perfectly RESTful, we might request two endpoints: `/todos` and `/users`:
|
|
775
|
+
|
|
776
|
+
```js
|
|
777
|
+
// Todo
|
|
778
|
+
{
|
|
779
|
+
id: "todo1234"
|
|
780
|
+
name: "My Todo",
|
|
781
|
+
created_by: "user1234"
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// User
|
|
785
|
+
{
|
|
786
|
+
id: "user1234"
|
|
787
|
+
name: "Bob Donut"
|
|
788
|
+
}
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
Our components would make requests to both and do the join on the client to display the name:
|
|
792
|
+
|
|
793
|
+
```js
|
|
794
|
+
const userName = usersCollection.get(todoModel.get("created_by"))?.get("name");
|
|
795
|
+
```
|
|
796
|
+
|
|
797
|
+
But there are valid reasons why we might want to instead be _less_ RESTful by returning the user's name directly with the TODO:
|
|
798
|
+
|
|
799
|
+
1. If a user leaves the organization, the TODO remains, and we still need to know who created it
|
|
800
|
+
2. It's just easier; now the client only has to make one request without any joins
|
|
801
|
+
|
|
802
|
+
In this case, the TODO may look like:
|
|
803
|
+
|
|
804
|
+
```js
|
|
805
|
+
{
|
|
806
|
+
id: "todo1234"
|
|
807
|
+
name: "My Todo",
|
|
808
|
+
created_by: {
|
|
809
|
+
id: "user1234",
|
|
810
|
+
name: "Bob Donut"
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
```
|
|
814
|
+
|
|
815
|
+
But what happens if Mr Bob Donut goes into the app and updates his name?
|
|
816
|
+
|
|
817
|
+
```js
|
|
818
|
+
usersCollection.get("user1234")?.save({name: "Mr Bob Donuts"}).catch(() => ...);
|
|
819
|
+
```
|
|
820
|
+
|
|
821
|
+
The Todos on the page, reading only from `/todos`, will still show `"Bob Donut"`. This is where CanonicalModels come in.
|
|
822
|
+
|
|
823
|
+
CanonicalModels are a new class of model that exist solely to act as third-party mediatators for pub-sub between models of the same class at the same id. First, you create a new canonical model class - these are generally not extended with any additional or custom members, and so all your canonical models can live in the same file:
|
|
824
|
+
|
|
825
|
+
```ts
|
|
826
|
+
// canonical-models.js
|
|
827
|
+
import type {User} from "types";
|
|
828
|
+
import {CanonicalModel} from "resourcerer";
|
|
829
|
+
|
|
830
|
+
export class CanonicalUserModel extends CanonicalModel<User> {}
|
|
831
|
+
```
|
|
832
|
+
|
|
833
|
+
Then we want to add a subscription on both the `TodosCollection` and the `UsersCollection` to tell them _how_ they should update when one changes:
|
|
834
|
+
|
|
835
|
+
```ts
|
|
836
|
+
import type { CanonicalModelSubscription } from "resourcerer";
|
|
837
|
+
|
|
838
|
+
// todos-collection.js
|
|
839
|
+
export class TodosCollection extends Collection<Todo> {
|
|
840
|
+
// this is an array, because a model or collection can have as many subscriptions as it needs
|
|
841
|
+
static subscriptions: [CanonicalModelSubscription<Todo, User>] = [{
|
|
842
|
+
// which model class we listen to updates on
|
|
843
|
+
Model: CanonicalUserModel,
|
|
844
|
+
// this is the field in Todo that corresponds to the id field for User. Dot-separated for nested strings.
|
|
845
|
+
// defaults to the idAttribute
|
|
846
|
+
idField: "created_by.id",
|
|
847
|
+
// takes an object of type User (the source) and returns the object that should be merged on the Todo
|
|
848
|
+
fromSource: (attrs) => ({
|
|
849
|
+
created_by: attrs.id,
|
|
850
|
+
name: attrs.name
|
|
851
|
+
})
|
|
852
|
+
}]
|
|
853
|
+
|
|
854
|
+
// ...
|
|
855
|
+
}
|
|
856
|
+
```
|
|
857
|
+
|
|
858
|
+
There is also a `toSource` option here that does the inverse - takes a Todo type and returns the type of the CanonicalModel (`User`, in this case), but since we are not writing from the Todo onto the canonical model (just reading), we don't need that here. We need that on the UsersCollection. Because the UsersCollection user is the same type as our CanonicalUserModel, this is a little bit simpler:
|
|
859
|
+
|
|
860
|
+
```ts
|
|
861
|
+
import type { CanonicalModelSubscription } from "resourcerer";
|
|
862
|
+
|
|
863
|
+
export class UsersCollection extends Collection<User> {
|
|
864
|
+
static subscriptions: [CanonicalModelSubscription<User, User>] = [{
|
|
865
|
+
Model: CanonicalUserModel,
|
|
866
|
+
idField: "id",
|
|
867
|
+
// because the types are the same from this model to the canonical, we want all updates on the user
|
|
868
|
+
// to update the canonical model identically
|
|
869
|
+
toSource: (attrs) => attrs,
|
|
870
|
+
fromSource: (attrs) => attrs
|
|
871
|
+
}]
|
|
872
|
+
|
|
873
|
+
// ...
|
|
874
|
+
}
|
|
875
|
+
```
|
|
876
|
+
|
|
877
|
+
With this simple change, when Bob Donut changes his name, the TodosCollection will get updated automatically in the app if it is in the cache! At its core, this is just pub/sub. Here's a breakdown of what happens:
|
|
878
|
+
|
|
879
|
+
* The user model gets updated with the new name as the request is sent to the server
|
|
880
|
+
* There is a `CanonicalUserModel` instance for each id in the `usersCollection`, and the one keyed at this id is listening on changes. It gets updated based on the result of the `toSource` function
|
|
881
|
+
* Each entry in the `todosCollection` is listening for changes in the `CanonicalUserModel` instance at its id field. So when the instance is updated, the `todoModel` gets updated with the result of the `fromSource` function
|
|
882
|
+
* When the `todoModel` updates, its component re-renders.
|
|
883
|
+
|
|
884
|
+
Ta-da! This is really a magical client-side syncing experience.
|
|
885
|
+
|
|
886
|
+
Two final notes:
|
|
887
|
+
|
|
888
|
+
1. The above subscription definition on the `UsersCollection` is what we want any time a model is its own canonical representation. So we have a shorthand. The above is equivalent to setting a `static CanonicalModel` property on the class:
|
|
889
|
+
|
|
890
|
+
```ts
|
|
891
|
+
export class UsersCollection extends Collection<User> {
|
|
892
|
+
static CanonicalModel = CanonicalUserModel;
|
|
893
|
+
}
|
|
894
|
+
```
|
|
895
|
+
|
|
896
|
+
2. `subscriptions` and `CanonicalModel` static properties can also be set on `Model` definitions.
|
|
897
|
+
|
|
898
|
+
|
|
768
899
|
# Differences between useResources and withResources
|
|
769
900
|
|
|
770
901
|
The hook and HOC largely operate interchangeably, but do note a couple critical differences:
|
|
@@ -33,6 +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
|
+
url: (options: typeof this.urlOptions) => string;
|
|
36
37
|
toJSON(): T[];
|
|
37
38
|
sync(...args: Parameters<typeof sync>): Promise<[any, Response]>;
|
|
38
39
|
add(models: ModelArg<T, O> | ModelArg<T, O>[], options?: CSetOptions): this;
|
|
@@ -3,7 +3,7 @@ import Model from "./model.js";
|
|
|
3
3
|
import { ResourceKeys } from "./types.js";
|
|
4
4
|
type Component = NonNullable<unknown>;
|
|
5
5
|
declare const ModelCache: {
|
|
6
|
-
get(cacheKey: string): Collection<object, object, {
|
|
6
|
+
get(cacheKey: string): Model<Record<string, any>, Record<string, any>> | Collection<object, object, {
|
|
7
7
|
new (attributes?: object | undefined, options?: object & import("./model.js").SetOptions & import("./model.js").ConstructorOptions): Model<object, object>;
|
|
8
8
|
idAttribute: string;
|
|
9
9
|
dependencies: (string | ((attrs: Record<string, any>) => Record<string, any>))[];
|
|
@@ -12,7 +12,7 @@ declare const ModelCache: {
|
|
|
12
12
|
measure: boolean | ((config: import("./types.js").ResourceConfigObj) => boolean);
|
|
13
13
|
subscriptions: import("./model.js").CanonicalModelSubscription<Record<string, any>, Record<string, any>>[];
|
|
14
14
|
CanonicalModel: (new (...args: any[]) => import("./canonical-model.js").default<any>) | null;
|
|
15
|
-
}> |
|
|
15
|
+
}> | undefined;
|
|
16
16
|
put(cacheKey: string, model: Model | Collection, component?: Component): void;
|
|
17
17
|
register(cacheKey: string, component?: Component): void;
|
|
18
18
|
unregister(component: Component, ...cacheKeys: string[]): void;
|
package/build/lib/model.js
CHANGED
|
@@ -169,11 +169,13 @@ export default class Model extends Events {
|
|
|
169
169
|
}
|
|
170
170
|
url(options = this.urlOptions) {
|
|
171
171
|
const base = result(this, "urlRoot", options) || result(this.collection, "url", options) || urlError();
|
|
172
|
+
const { pathname, searchParams } = new URL(base, window.location.origin);
|
|
172
173
|
if (this.isNew()) {
|
|
173
174
|
return base;
|
|
174
175
|
}
|
|
175
|
-
return (
|
|
176
|
-
window.encodeURIComponent(this.get(this.constructor.idAttribute))
|
|
176
|
+
return (pathname.replace(/[^/]$/, "$&/") +
|
|
177
|
+
window.encodeURIComponent(this.get(this.constructor.idAttribute)) +
|
|
178
|
+
`${searchParams.toString() ? `?${searchParams.toString()}` : ""}`);
|
|
177
179
|
}
|
|
178
180
|
parse(response, options) {
|
|
179
181
|
return response;
|
package/build/lib/request.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ interface RequestOptions extends Pick<SyncOptions, "params"> {
|
|
|
10
10
|
force?: boolean;
|
|
11
11
|
lazy?: boolean;
|
|
12
12
|
}
|
|
13
|
-
export declare const getFromCache: (key: string) => Collection<object, object, {
|
|
13
|
+
export declare const getFromCache: (key: string) => Model<Record<string, any>, Record<string, any>> | Collection<object, object, {
|
|
14
14
|
new (attributes?: object | undefined, options?: object & import("./model.js").SetOptions & import("./model.js").ConstructorOptions): Model<object, object>;
|
|
15
15
|
idAttribute: string;
|
|
16
16
|
dependencies: (string | ((attrs: Record<string, any>) => Record<string, any>))[];
|
|
@@ -19,7 +19,7 @@ export declare const getFromCache: (key: string) => Collection<object, object, {
|
|
|
19
19
|
measure: boolean | ((config: import("./types.js").ResourceConfigObj) => boolean);
|
|
20
20
|
subscriptions: import("./model.js").CanonicalModelSubscription<Record<string, any>, Record<string, any>>[];
|
|
21
21
|
CanonicalModel: (new (...args: any[]) => import("./canonical-model.js").default<any>) | null;
|
|
22
|
-
}> |
|
|
22
|
+
}> | undefined;
|
|
23
23
|
export declare const existsInCache: (key: string) => boolean;
|
|
24
24
|
declare const _default: (key: string, Model: {
|
|
25
25
|
new (data: Record<string, any>, options: RequestOptions["options"]): Model;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "resourcerer",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "github.com/noahgrant/resourcerer"
|
|
@@ -34,19 +34,21 @@
|
|
|
34
34
|
},
|
|
35
35
|
"exports": "./build/index.js",
|
|
36
36
|
"devDependencies": {
|
|
37
|
-
"@eslint/
|
|
38
|
-
"@
|
|
37
|
+
"@eslint/eslintrc": "^3.3.5",
|
|
38
|
+
"@eslint/js": "^10.0.1",
|
|
39
39
|
"@types/eslint__js": "^8.42.3",
|
|
40
40
|
"@types/react": "^18.3.3",
|
|
41
41
|
"@types/react-dom": "^18.3.0",
|
|
42
|
+
"@typescript-eslint/eslint-plugin": "^8.57.0",
|
|
42
43
|
"@vitejs/plugin-react": "^4.3.1",
|
|
43
44
|
"@vitest/coverage-v8": "^1.6.0",
|
|
44
|
-
"eslint": "^
|
|
45
|
-
"eslint-config-prettier": "^
|
|
46
|
-
"
|
|
45
|
+
"eslint": "^10.0.3",
|
|
46
|
+
"eslint-config-prettier": "^10.1.8",
|
|
47
|
+
"globals": "^17.4.0",
|
|
48
|
+
"jsdom": "^24.0.0",
|
|
47
49
|
"prettier": "^3.2.5",
|
|
48
50
|
"typescript": "^5.4.5",
|
|
49
|
-
"typescript-eslint": "^
|
|
51
|
+
"typescript-eslint": "^8.57.0",
|
|
50
52
|
"vitest": "^1.6.0"
|
|
51
53
|
},
|
|
52
54
|
"peerDependencies": {
|
package/test/config.test.js
CHANGED
package/test/model.test.js
CHANGED
|
@@ -470,19 +470,36 @@ describe("Model", () => {
|
|
|
470
470
|
expect(model.url()).toEqual("/library");
|
|
471
471
|
});
|
|
472
472
|
|
|
473
|
-
|
|
473
|
+
describe("appends its id to the url if not new", () => {
|
|
474
474
|
class _Model extends Model {
|
|
475
475
|
static idAttribute = "name";
|
|
476
476
|
}
|
|
477
477
|
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
478
|
+
beforeEach(() => {
|
|
479
|
+
vi.stubGlobal("location", { origin: "https://bobsdonuts.com" });
|
|
480
|
+
});
|
|
481
481
|
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
482
|
+
it("when there are no query params", () => {
|
|
483
|
+
model = new _Model({ name: "noah?grant" });
|
|
484
|
+
model.urlRoot = () => "/library";
|
|
485
|
+
expect(model.url()).toEqual("/library/noah%3Fgrant");
|
|
486
|
+
|
|
487
|
+
collection = new Collection();
|
|
488
|
+
collection.url = () => "/library";
|
|
489
|
+
model = new _Model({ name: "noah?grant" }, { collection });
|
|
490
|
+
expect(model.url()).toEqual("/library/noah%3Fgrant");
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
it("when there are query params attached to the url", () => {
|
|
494
|
+
model = new _Model({ name: "noah?grant" });
|
|
495
|
+
model.urlRoot = () => "/library?foo=bar";
|
|
496
|
+
expect(model.url()).toEqual("/library/noah%3Fgrant?foo=bar");
|
|
497
|
+
|
|
498
|
+
collection = new Collection();
|
|
499
|
+
collection.url = () => "/library?foo=bar";
|
|
500
|
+
model = new _Model({ name: "noah?grant" }, { collection });
|
|
501
|
+
expect(model.url()).toEqual("/library/noah%3Fgrant?foo=bar");
|
|
502
|
+
});
|
|
486
503
|
});
|
|
487
504
|
|
|
488
505
|
it("is called by default with its urlOptions", () => {
|
package/test/request.test.js
CHANGED
|
@@ -8,7 +8,6 @@ import { vi } from "vitest";
|
|
|
8
8
|
const component = {};
|
|
9
9
|
const CACHE_WAIT = 150000;
|
|
10
10
|
|
|
11
|
-
/* eslint-disable max-nested-callbacks */
|
|
12
11
|
describe("Request", () => {
|
|
13
12
|
var waitSuccess, reject;
|
|
14
13
|
|
|
@@ -360,4 +359,3 @@ function unregisterComponent(comp) {
|
|
|
360
359
|
vi.advanceTimersByTime(CACHE_WAIT);
|
|
361
360
|
vi.useRealTimers();
|
|
362
361
|
}
|
|
363
|
-
/* eslint-enable max-nested-callbacks */
|