resourcerer 2.2.1 → 2.3.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.
@@ -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) {
@@ -33,7 +33,6 @@ 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;
37
36
  toJSON(): T[];
38
37
  sync(...args: Parameters<typeof sync>): Promise<[any, Response]>;
39
38
  add(models: ModelArg<T, O> | ModelArg<T, O>[], options?: CSetOptions): this;
@@ -44,6 +43,7 @@ export default class Collection<T extends Record<string, any> = object, O extend
44
43
  has(obj: Model<T, O>["id"] | ModelArg<T, O>): boolean;
45
44
  at(index: number): InstanceType<this["Model"]> | undefined;
46
45
  map(predicate: (model: InstanceType<this["Model"]>) => any): any[];
46
+ forEach(predicate: (model: InstanceType<this["Model"]>) => void): void;
47
47
  find(predicate: (model: InstanceType<this["Model"]>) => boolean): InstanceType<M> | undefined;
48
48
  filter(predicate: (model: InstanceType<this["Model"]>) => boolean): InstanceType<M>[];
49
49
  findWhere(attrs: Partial<T>): InstanceType<this["Model"]> | undefined;
@@ -66,4 +66,5 @@ export default class Collection<T extends Record<string, any> = object, O extend
66
66
  _removeReference(model: Model<T, O>): void;
67
67
  _updateModelReference(id: string | number, prevId: string | number, model: InstanceType<M>): void;
68
68
  }
69
+ export type CollectionConstructor = abstract new (...args: any[]) => Collection;
69
70
  export {};
@@ -109,6 +109,9 @@ export default class Collection extends Events {
109
109
  map(predicate) {
110
110
  return this.models.map(predicate);
111
111
  }
112
+ forEach(predicate) {
113
+ this.models.forEach(predicate);
114
+ }
112
115
  find(predicate) {
113
116
  return this.models.find(predicate);
114
117
  }
@@ -3,16 +3,16 @@ 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): Model<Record<string, any>, Record<string, any>> | Collection<object, object, {
6
+ get(cacheKey: string): 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
- dependencies: (string | ((attrs: Record<string, any>) => Record<string, any>))[];
9
+ dependencies: Array<string | ((attrs: Record<string, any>) => Record<string, any>)>;
10
10
  cacheTimeout: number;
11
11
  defaults: {};
12
12
  measure: boolean | ((config: import("./types.js").ResourceConfigObj) => boolean);
13
- subscriptions: import("./model.js").CanonicalModelSubscription<Record<string, any>, Record<string, any>>[];
13
+ subscriptions: import("./model.js").CanonicalModelSubscription[];
14
14
  CanonicalModel: (new (...args: any[]) => import("./canonical-model.js").default<any>) | null;
15
- }> | undefined;
15
+ }> | Model<Record<string, any>, Record<string, any>> | 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;
@@ -1,6 +1,6 @@
1
1
  import Events from "./events.js";
2
2
  import sync, { type SyncOptions } from "./sync.js";
3
- import Collection from "./collection.js";
3
+ import Collection, { type CollectionConstructor } from "./collection.js";
4
4
  import { NestedKeys, ResourceConfigObj } from "./types.js";
5
5
  import CanonicalModel from "./canonical-model.js";
6
6
  export type ConstructorOptions = {
@@ -58,6 +58,7 @@ export default class Model<T extends Record<string, any> = Record<string, any>,
58
58
  isNew(): boolean;
59
59
  _subscribe(attrs?: Partial<T>): void;
60
60
  unsubscribe(): void;
61
+ _removePeerSubscribers(CollectionClass?: CollectionConstructor): void;
61
62
  _updateSubscriptions(attrs?: Partial<T>, options?: SetOptions): void;
62
63
  _getSubscriptions(): (CanonicalModelSubscription<Record<string, any>, Record<string, any>> | {
63
64
  Model: new (...args: any[]) => CanonicalModel<any>;
@@ -147,6 +147,7 @@ export default class Model extends Events {
147
147
  const request = this.isNew() ?
148
148
  Promise.resolve([])
149
149
  : this.sync(this, { method: "DELETE", ...options }), collection = this.collection;
150
+ const CollectionClass = collection?.constructor;
150
151
  if (!options.wait) {
151
152
  this.triggerUpdate();
152
153
  this.collection?.remove(this, { silent: true });
@@ -157,6 +158,9 @@ export default class Model extends Events {
157
158
  this.triggerUpdate();
158
159
  this.collection?.remove(this, { silent: true });
159
160
  }
161
+ if (!this.isNew()) {
162
+ this._removePeerSubscribers(CollectionClass);
163
+ }
160
164
  this.unsubscribe();
161
165
  return [this, response];
162
166
  })
@@ -213,6 +217,23 @@ export default class Model extends Events {
213
217
  }
214
218
  }
215
219
  }
220
+ _removePeerSubscribers(CollectionClass) {
221
+ if (!CollectionClass) {
222
+ return;
223
+ }
224
+ const subscriptions = this._getSubscriptions();
225
+ const idAttribute = this.constructor.idAttribute;
226
+ for (const { Model: CanonicalModel, idField = idAttribute } of subscriptions) {
227
+ if (idField !== idAttribute) {
228
+ continue;
229
+ }
230
+ const id = getNestedValue(this.toJSON(), idField);
231
+ if (id && !this.isEmptyModel) {
232
+ const canonicalModel = CanonicalModelCache.getOrInsert(CanonicalModel, id);
233
+ canonicalModel.removeSubscribersFromCollection(CollectionClass, this);
234
+ }
235
+ }
236
+ }
216
237
  _updateSubscriptions(attrs = {}, options = {}) {
217
238
  const subscriptions = this._getSubscriptions();
218
239
  const idAttribute = this.constructor.idAttribute;
@@ -10,16 +10,16 @@ interface RequestOptions extends Pick<SyncOptions, "params"> {
10
10
  force?: boolean;
11
11
  lazy?: boolean;
12
12
  }
13
- export declare const getFromCache: (key: string) => Model<Record<string, any>, Record<string, any>> | Collection<object, object, {
13
+ export declare const getFromCache: (key: string) => 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
- dependencies: (string | ((attrs: Record<string, any>) => Record<string, any>))[];
16
+ dependencies: Array<string | ((attrs: Record<string, any>) => Record<string, any>)>;
17
17
  cacheTimeout: number;
18
18
  defaults: {};
19
19
  measure: boolean | ((config: import("./types.js").ResourceConfigObj) => boolean);
20
- subscriptions: import("./model.js").CanonicalModelSubscription<Record<string, any>, Record<string, any>>[];
20
+ subscriptions: import("./model.js").CanonicalModelSubscription[];
21
21
  CanonicalModel: (new (...args: any[]) => import("./canonical-model.js").default<any>) | null;
22
- }> | undefined;
22
+ }> | Model<Record<string, any>, Record<string, any>> | 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;
@@ -12,6 +12,6 @@ export declare function useResources<T extends ResourceKeys, O extends Record<st
12
12
  [Key in T as `${T}Status`]: number;
13
13
  };
14
14
  export declare const withResources: (getResources: ExecutorFunction) => (Component: ComponentClass<Record<string, any>>) => (props: Record<string, any>) => React.CElement<{
15
- children: React.ReactElement<any, string | React.JSXElementConstructor<any>>;
15
+ children: React.ReactElement;
16
16
  }, ErrorBoundary>;
17
17
  export declare function getCacheKey({ resourceKey, params, path, data, }: InternalResourceConfigObj): string;
@@ -224,6 +224,13 @@ map: (predicate: (Model) => any) => any[]
224
224
 
225
225
  Same signature as Array.prototype.map across a collection's models.
226
226
 
227
+ ### forEach
228
+ ```js
229
+ forEach: (predicate: (Model) => void) => void
230
+ ```
231
+
232
+ Same signature as Array.prototype.forEach across a collection's models.
233
+
227
234
  ### pluck
228
235
  ```js
229
236
  pluck: (attribute: string) => any[]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "2.2.1",
3
+ "version": "2.3.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "github.com/noahgrant/resourcerer"
@@ -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
 
@@ -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);
@@ -454,6 +454,180 @@ describe("Model", () => {
454
454
  expect(err).toEqual(response);
455
455
  }
456
456
  });
457
+
458
+ describe("peer collections", () => {
459
+ class CanonicalUserModel extends CanonicalModel {}
460
+
461
+ class UsersCollection extends Collection {
462
+ static CanonicalModel = CanonicalUserModel;
463
+
464
+ url() {
465
+ return "/users";
466
+ }
467
+ }
468
+
469
+ class UserDetailsCollection extends Collection {
470
+ static CanonicalModel = CanonicalUserModel;
471
+
472
+ url() {
473
+ return "/user-details";
474
+ }
475
+ }
476
+
477
+ afterEach(() => {
478
+ canonicalModelCache.clear();
479
+ });
480
+
481
+ it("removes the model from other instances of the same collection class after DELETE succeeds", async () => {
482
+ const activeUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
483
+ const allUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
484
+ const userDetails = new UserDetailsCollection([{ id: "1234", name: "Bob" }]);
485
+
486
+ await activeUsers.get("1234").destroy();
487
+
488
+ expect(activeUsers.has("1234")).toBe(false);
489
+ expect(allUsers.has("1234")).toBe(false);
490
+ expect(userDetails.has("1234")).toBe(true);
491
+ });
492
+
493
+ it("removes peers only after the request resolves when `wait` is true", async () => {
494
+ const activeUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
495
+ const allUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
496
+
497
+ model = activeUsers.get("1234");
498
+ const request = model.destroy({ wait: true });
499
+
500
+ expect(allUsers.has("1234")).toBe(true);
501
+ await request;
502
+ expect(allUsers.has("1234")).toBe(false);
503
+ });
504
+
505
+ it("does not remove peers when the request rejects", async () => {
506
+ sync.default.mockRejectedValue(response);
507
+
508
+ const activeUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
509
+ const allUsers = new UsersCollection([{ id: "1234", name: "Bob" }]);
510
+
511
+ model = activeUsers.get("1234");
512
+
513
+ try {
514
+ await model.destroy();
515
+ } catch (err) {
516
+ expect(allUsers.has("1234")).toBe(true);
517
+ expect(err).toEqual(response);
518
+ }
519
+ });
520
+
521
+ it("removes peers when the canonical model is defined on the model subscriptions", async () => {
522
+ class User extends Model {
523
+ static subscriptions = [
524
+ {
525
+ Model: CanonicalUserModel,
526
+ toSource: (attrs) => attrs,
527
+ fromSource: (attrs) => attrs,
528
+ },
529
+ ];
530
+ }
531
+
532
+ class SubscriptionsUsersCollection extends Collection {
533
+ static Model = User;
534
+ }
535
+
536
+ const activeUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
537
+ const allUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
538
+
539
+ model = activeUsers.get("1234");
540
+ await model.destroy();
541
+
542
+ expect(allUsers.has("1234")).toBe(false);
543
+ });
544
+
545
+ it("does not remove peers when the canonical model id field and idAttribute are not equal", async () => {
546
+ class User extends Model {
547
+ static subscriptions = [
548
+ {
549
+ Model: CanonicalUserModel,
550
+ idField: "_id",
551
+ toSource: (attrs) => attrs,
552
+ fromSource: (attrs) => attrs,
553
+ },
554
+ ];
555
+ }
556
+
557
+ class SubscriptionsUsersCollection extends Collection {
558
+ static Model = User;
559
+ }
560
+
561
+ const activeUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
562
+ const allUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
563
+
564
+ model = activeUsers.get("1234");
565
+ await model.destroy();
566
+
567
+ // canonical model subscription has an id field that does not equal idAttribute,
568
+ // so it is not removed
569
+ expect(allUsers.has("1234")).toBe(true);
570
+ });
571
+
572
+ it("removes peers when the canonical model id field and idAttribute are not the default 'id'", async () => {
573
+ class User extends Model {
574
+ static subscriptions = [
575
+ {
576
+ Model: CanonicalUserModel,
577
+ idField: "_id",
578
+ toSource: (attrs) => attrs,
579
+ fromSource: (attrs) => attrs,
580
+ },
581
+ ];
582
+
583
+ static idAttribute = "_id";
584
+ }
585
+
586
+ class SubscriptionsUsersCollection extends Collection {
587
+ static Model = User;
588
+ }
589
+
590
+ const activeUsers = new SubscriptionsUsersCollection([{ _id: "1234", name: "Bob" }]);
591
+ const allUsers = new SubscriptionsUsersCollection([{ _id: "1234", name: "Bob" }]);
592
+
593
+ model = activeUsers.get("1234");
594
+ await model.destroy();
595
+
596
+ expect(allUsers.has("1234")).toBe(false);
597
+ });
598
+
599
+ it("removes peers when the canonical model is defined on the collection", async () => {
600
+ class SubscriptionsUsersCollection extends Collection {
601
+ static CanonicalModel = CanonicalUserModel;
602
+ }
603
+
604
+ const activeUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
605
+ const allUsers = new SubscriptionsUsersCollection([{ id: "1234", name: "Bob" }]);
606
+
607
+ model = activeUsers.get("1234");
608
+ await model.destroy();
609
+
610
+ expect(allUsers.has("1234")).toBe(false);
611
+ });
612
+
613
+ it("removes peers when the canonical model is defined on the model class", async () => {
614
+ class User extends Model {
615
+ static CanonicalModel = CanonicalUserModel;
616
+ }
617
+
618
+ class ModelUsersCollection extends Collection {
619
+ static Model = User;
620
+ }
621
+
622
+ const activeUsers = new ModelUsersCollection([{ id: "1234", name: "Bob" }]);
623
+ const allUsers = new ModelUsersCollection([{ id: "1234", name: "Bob" }]);
624
+
625
+ model = activeUsers.get("1234");
626
+ await model.destroy();
627
+
628
+ expect(allUsers.has("1234")).toBe(false);
629
+ });
630
+ });
457
631
  });
458
632
 
459
633
  describe("url", () => {