resourcerer 2.0.6 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { default as Collection } from "./lib/collection.js";
2
- export { default as Model } from "./lib/model.js";
2
+ export { default as CanonicalModel } from "./lib/canonical-model.js";
3
+ export { default as Model, type CanonicalModelSubscription } from "./lib/model.js";
3
4
  export { default as sync, ajax, type SyncOptions } from "./lib/sync.js";
4
5
  export { default as prefetch } from "./lib/prefetch.js";
5
6
  export { default as request } from "./lib/request.js";
package/build/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { default as Collection } from "./lib/collection.js";
2
+ export { default as CanonicalModel } from "./lib/canonical-model.js";
2
3
  export { default as Model } from "./lib/model.js";
3
4
  export { default as sync, ajax } from "./lib/sync.js";
4
5
  export { default as prefetch } from "./lib/prefetch.js";
@@ -0,0 +1,8 @@
1
+ import CanonicalModel from "./canonical-model.js";
2
+ export declare const canonicalModelCache: Map<typeof CanonicalModel<any>, Map<string | number, CanonicalModel<any>>>;
3
+ declare const CanonicalModelCache: {
4
+ getOrInsert(ModelClass: typeof CanonicalModel<any>, id: string | number): CanonicalModel<any>;
5
+ set(ModelClass: typeof CanonicalModel<any>, id: string | number, model: CanonicalModel<any>): void;
6
+ remove(ModelClass: typeof CanonicalModel<any>, id: string | number): void;
7
+ };
8
+ export default CanonicalModelCache;
@@ -0,0 +1,24 @@
1
+ export const canonicalModelCache = new Map();
2
+ const CanonicalModelCache = {
3
+ getOrInsert(ModelClass, id) {
4
+ const existingCachedModel = canonicalModelCache.get(ModelClass)?.get(id);
5
+ if (existingCachedModel) {
6
+ return existingCachedModel;
7
+ }
8
+ const newCanonicalModel = new ModelClass();
9
+ this.set(ModelClass, id, newCanonicalModel);
10
+ return newCanonicalModel;
11
+ },
12
+ set(ModelClass, id, model) {
13
+ const canonicalModelMap = canonicalModelCache.get(ModelClass) || new Map();
14
+ canonicalModelMap.set(id, model);
15
+ canonicalModelCache.set(ModelClass, canonicalModelMap);
16
+ },
17
+ remove(ModelClass, id) {
18
+ const canonicalModelMap = canonicalModelCache.get(ModelClass);
19
+ if (canonicalModelMap) {
20
+ canonicalModelMap.delete(id);
21
+ }
22
+ },
23
+ };
24
+ export default CanonicalModelCache;
@@ -0,0 +1,14 @@
1
+ import Events from "./events.js";
2
+ import Model from "./model.js";
3
+ export default class CanonicalModel<T extends Record<string, any>> extends Events<[
4
+ Partial<T>,
5
+ Model
6
+ ]> {
7
+ attributes: T;
8
+ get<K extends keyof T>(attr: K): T[K];
9
+ set(attrs: Partial<T> | undefined, context: Model, options?: {
10
+ unset?: boolean;
11
+ }): void;
12
+ removeSubscription(context: Model<any, any>, id: string | number): void;
13
+ toJSON(): T;
14
+ }
@@ -0,0 +1,33 @@
1
+ import { isDeepEqual } from "./utils.js";
2
+ import Events from "./events.js";
3
+ import CanonicalModelCache from "./canonical-model-cache.js";
4
+ export default class CanonicalModel extends Events {
5
+ attributes = {};
6
+ get(attr) {
7
+ return this.attributes[attr];
8
+ }
9
+ set(attrs = {}, context, options = {}) {
10
+ let hasSomethingChanged = false;
11
+ for (let attr of Object.keys(attrs)) {
12
+ if (!hasSomethingChanged && !isDeepEqual(this.attributes[attr], attrs[attr])) {
13
+ hasSomethingChanged = true;
14
+ }
15
+ options.unset ?
16
+ delete this.attributes[attr]
17
+ : (this.attributes[attr] = attrs[attr]);
18
+ }
19
+ if (hasSomethingChanged) {
20
+ this.triggerUpdate(this.toJSON(), context);
21
+ }
22
+ }
23
+ removeSubscription(context, id) {
24
+ this.offUpdate(context);
25
+ if (!this._callbacks.length) {
26
+ CanonicalModelCache.remove(this.constructor, id);
27
+ }
28
+ }
29
+ toJSON() {
30
+ return { ...this.attributes };
31
+ }
32
+ }
33
+ Object.assign(CanonicalModel.prototype, Events);
@@ -9,7 +9,7 @@ type CSetOptions = {
9
9
  } & SetOptions & ConstructorOptions;
10
10
  type ModelArg<A extends Record<string, any>, O extends Record<string, any>> = Model<A, O> | Record<string, any>;
11
11
  type comparator = string | ((arg: Model) => number | string) | ((arg1: Model, arg2?: Model) => number | undefined);
12
- export default class Collection<T extends Record<string, any> = object, O extends Record<string, any> = object, M extends typeof Model<T, O> = typeof Model<T, O>> extends Events {
12
+ export default class Collection<T extends Record<string, any> = object, O extends Record<string, any> = object, M extends typeof Model<T, O> = typeof Model<T, O>> extends Events<[]> {
13
13
  lazy?: boolean;
14
14
  refetching?: boolean;
15
15
  measure?: boolean | ((config: ResourceConfigObj) => boolean);
@@ -52,6 +52,7 @@ export default class Collection<T extends Record<string, any> = object, O extend
52
52
  wait?: boolean;
53
53
  } & SyncOptions & CSetOptions): Promise<[InstanceType<this["Model"]>, Response]>;
54
54
  parse(response: any, options: SyncOptions & CSetOptions): T[];
55
+ unsubscribe(): void;
55
56
  _getModelClass<T extends Record<string, any>, O extends Record<string, any>>(): typeof Model<T, O>;
56
57
  _reset(): void;
57
58
  _prepareModel(attrs: ModelArg<T, O>, options?: CSetOptions): Model<T, O>;
@@ -180,6 +180,9 @@ export default class Collection extends Events {
180
180
  parse(response, options) {
181
181
  return response;
182
182
  }
183
+ unsubscribe() {
184
+ this.models.forEach((model) => model.unsubscribe());
185
+ }
183
186
  _getModelClass() {
184
187
  if (this.constructor.idAttribute) {
185
188
  let attr = this.constructor.idAttribute;
@@ -241,6 +244,7 @@ export default class Collection extends Events {
241
244
  }
242
245
  delete model.collection;
243
246
  model.offUpdate(this);
247
+ model.unsubscribe();
244
248
  }
245
249
  _updateModelReference(id, prevId, model) {
246
250
  if (id) {
@@ -1,11 +1,11 @@
1
- type CallbackEntry = {
2
- callback: (...args: any[]) => void;
1
+ type CallbackEntry<Args extends any[]> = {
2
+ callback: (...args: Args) => void;
3
3
  context: NonNullable<unknown>;
4
4
  };
5
- export default class Events {
6
- _callbacks: CallbackEntry[];
7
- triggerUpdate(): void;
8
- onUpdate(callback: CallbackEntry["callback"], context: CallbackEntry["context"]): void;
9
- offUpdate(ctx: CallbackEntry["context"]): void;
5
+ export default class Events<Args extends any[] = []> {
6
+ _callbacks: CallbackEntry<Args>[];
7
+ triggerUpdate(...args: Args): void;
8
+ onUpdate(callback: CallbackEntry<Args>["callback"], context: CallbackEntry<Args>["context"]): void;
9
+ offUpdate(ctx: CallbackEntry<Args>["context"]): void;
10
10
  }
11
11
  export {};
@@ -1,7 +1,7 @@
1
1
  export default class Events {
2
2
  _callbacks = [];
3
- triggerUpdate() {
4
- this._callbacks?.forEach(({ callback, context }) => callback.call(context));
3
+ triggerUpdate(...args) {
4
+ this._callbacks?.forEach(({ callback, context }) => callback.call(context, ...args));
5
5
  }
6
6
  onUpdate(callback, context) {
7
7
  this._callbacks = (this._callbacks || []).concat({ callback, context });
@@ -10,6 +10,7 @@ declare const ModelCache: {
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
14
  }> | undefined;
14
15
  put(cacheKey: string, model: Model | Collection, component?: Component): void;
15
16
  register(cacheKey: string, component?: Component): void;
@@ -65,6 +65,7 @@ function scheduleForRemoval(cacheKey) {
65
65
  timeouts[cacheKey] = window.setTimeout(() => clearModel(cacheKey), timeout);
66
66
  }
67
67
  function clearModel(cacheKey) {
68
+ modelCache.get(cacheKey)?.unsubscribe();
68
69
  window.clearTimeout(timeouts[cacheKey]);
69
70
  delete timeouts[cacheKey];
70
71
  modelCache.delete(cacheKey);
@@ -1,16 +1,25 @@
1
1
  import Events from "./events.js";
2
2
  import sync, { type SyncOptions } from "./sync.js";
3
3
  import Collection from "./collection.js";
4
- import { ResourceConfigObj } from "./types.js";
4
+ import { NestedKeys, ResourceConfigObj } from "./types.js";
5
+ import CanonicalModel from "./canonical-model.js";
5
6
  export type ConstructorOptions = {
6
7
  collection?: Collection;
7
8
  parse?: boolean;
8
9
  };
10
+ export type CanonicalModelSubscription<M extends Record<string, any> = Record<string, any>, C extends Record<string, any> = Record<string, any>> = {
11
+ Model: typeof CanonicalModel<C>;
12
+ idField?: NestedKeys<M>;
13
+ fromSource?: (attrs: Partial<C>, currentTarget: Partial<M>) => Partial<M>;
14
+ toSource?: (attrs: Partial<M>, currentSource: Partial<C>) => Partial<C>;
15
+ };
9
16
  export type SetOptions = {
10
17
  silent?: boolean;
11
18
  unset?: boolean;
19
+ source?: "subscription" | "self";
20
+ subscribe?: boolean;
12
21
  };
13
- export default class Model<T extends Record<string, any> = Record<string, any>, O extends Record<string, any> = Record<string, any>> extends Events {
22
+ export default class Model<T extends Record<string, any> = Record<string, any>, O extends Record<string, any> = Record<string, any>> extends Events<[]> {
14
23
  cid: string;
15
24
  id: string | number;
16
25
  attributes: T;
@@ -20,12 +29,13 @@ export default class Model<T extends Record<string, any> = Record<string, any>,
20
29
  refetching?: boolean;
21
30
  measure?: boolean | ((config: ResourceConfigObj) => boolean);
22
31
  isEmptyModel?: boolean;
23
- constructor(attributes?: T, options?: O & SetOptions & ConstructorOptions);
32
+ constructor(attributes?: Partial<T>, options?: O & SetOptions & ConstructorOptions);
24
33
  static idAttribute: string;
25
34
  static dependencies: Array<string | ((attrs: Record<string, any>) => Record<string, any>)>;
26
35
  static cacheTimeout: number;
27
36
  static defaults: {};
28
37
  static measure: boolean | ((config: ResourceConfigObj) => boolean);
38
+ static subscriptions: CanonicalModelSubscription[];
29
39
  toJSON(): T;
30
40
  sync(...args: Parameters<typeof sync>): Promise<[any, Response]>;
31
41
  get<K extends keyof T>(attr: K): T[K];
@@ -45,4 +55,7 @@ export default class Model<T extends Record<string, any> = Record<string, any>,
45
55
  url(options?: O): string;
46
56
  parse(response: any, options: SyncOptions & SetOptions): T;
47
57
  isNew(): boolean;
58
+ _subscribe(attrs?: Partial<T>): void;
59
+ unsubscribe(): void;
60
+ _updateSubscriptions(attrs?: Partial<T>, options?: SetOptions): void;
48
61
  }
@@ -1,6 +1,7 @@
1
- import { isDeepEqual, result, uniqueId, urlError } from "./utils.js";
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 CanonicalModelCache from "./canonical-model-cache.js";
4
5
  const RESERVED_OPTION_KEYS = [
5
6
  "Model",
6
7
  "comparator",
@@ -31,13 +32,18 @@ export default class Model extends Events {
31
32
  attributes = this.parse(attributes, options) || {};
32
33
  }
33
34
  this.urlOptions = Object.keys(options).reduce((memo, key) => Object.assign(memo, !RESERVED_OPTION_KEYS.includes(key) ? { [key]: options[key] } : {}), {});
34
- this.set({ ...result(this.constructor, "defaults"), ...attributes }, options);
35
+ const attrs = { ...result(this.constructor, "defaults"), ...attributes };
36
+ if (options.subscribe !== false) {
37
+ this._subscribe(attrs);
38
+ }
39
+ this.set(attrs, options);
35
40
  }
36
41
  static idAttribute = "id";
37
42
  static dependencies = [];
38
43
  static cacheTimeout;
39
44
  static defaults = {};
40
45
  static measure = false;
46
+ static subscriptions = [];
41
47
  toJSON() {
42
48
  return { ...this.attributes };
43
49
  }
@@ -64,6 +70,9 @@ export default class Model extends Events {
64
70
  delete this.attributes[attr]
65
71
  : (this.attributes[attr] = attrs[attr]);
66
72
  }
73
+ if (hasSomethingChanged && options.source !== "subscription" && options.subscribe !== false) {
74
+ this._updateSubscriptions(attrs, options);
75
+ }
67
76
  if (this.constructor.idAttribute in attrs) {
68
77
  this.id = this.get(this.constructor.idAttribute);
69
78
  }
@@ -89,6 +98,7 @@ export default class Model extends Events {
89
98
  options = { parse: true, method: "GET", ...options };
90
99
  return this.sync(this, options).then(([json, response]) => {
91
100
  const serverAttrs = options.parse ? this.parse(json, options) : json;
101
+ this._subscribe(serverAttrs);
92
102
  this.set(serverAttrs, options);
93
103
  this.triggerUpdate();
94
104
  return [this, response];
@@ -117,6 +127,7 @@ export default class Model extends Events {
117
127
  if (options.wait) {
118
128
  serverAttrs = { ...attrs, ...serverAttrs };
119
129
  }
130
+ this._subscribe(serverAttrs);
120
131
  this.set(serverAttrs, { silent: true, ...options });
121
132
  this.triggerUpdate();
122
133
  return [this, response];
@@ -132,7 +143,9 @@ export default class Model extends Events {
132
143
  });
133
144
  }
134
145
  destroy(options = {}) {
135
- const request = this.isNew() ? Promise.resolve([]) : this.sync(this, { method: "DELETE", ...options }), collection = this.collection;
146
+ const request = this.isNew() ?
147
+ Promise.resolve([])
148
+ : this.sync(this, { method: "DELETE", ...options }), collection = this.collection;
136
149
  if (!options.wait) {
137
150
  this.triggerUpdate();
138
151
  this.collection?.remove(this, { silent: true });
@@ -142,6 +155,7 @@ export default class Model extends Events {
142
155
  if (options.wait && !this.isNew()) {
143
156
  this.triggerUpdate();
144
157
  this.collection?.remove(this, { silent: true });
158
+ this.unsubscribe();
145
159
  }
146
160
  return [this, response];
147
161
  })
@@ -166,5 +180,43 @@ export default class Model extends Events {
166
180
  isNew() {
167
181
  return !this.has(this.constructor.idAttribute);
168
182
  }
183
+ _subscribe(attrs = {}) {
184
+ const { subscriptions, idAttribute } = this.constructor;
185
+ for (const { Model: CanonicalModel, idField = idAttribute, fromSource } of subscriptions) {
186
+ const id = getNestedValue(this.toJSON(), idField) || getNestedValue(attrs || {}, idField);
187
+ if (id && !this.isEmptyModel) {
188
+ const canonicalModel = CanonicalModelCache.getOrInsert(CanonicalModel, id);
189
+ canonicalModel.offUpdate(this);
190
+ canonicalModel.onUpdate((canonicalAttrs, context) => {
191
+ if (context === this || !fromSource) {
192
+ return;
193
+ }
194
+ this.set(fromSource(canonicalAttrs, this.toJSON()), {
195
+ source: "subscription",
196
+ });
197
+ }, this);
198
+ }
199
+ }
200
+ }
201
+ unsubscribe() {
202
+ const { subscriptions, idAttribute } = this.constructor;
203
+ for (const { Model: CanonicalModel, idField = idAttribute } of subscriptions) {
204
+ const id = getNestedValue(this.toJSON(), idField);
205
+ if (id) {
206
+ const canonicalModel = CanonicalModelCache.getOrInsert(CanonicalModel, id);
207
+ canonicalModel.removeSubscription(this, id);
208
+ }
209
+ }
210
+ }
211
+ _updateSubscriptions(attrs = {}, options = {}) {
212
+ const { subscriptions, idAttribute } = this.constructor;
213
+ for (const { Model: CanonicalModel, idField = idAttribute, toSource } of subscriptions) {
214
+ const id = getNestedValue(this.toJSON(), idField) || getNestedValue(attrs, idField);
215
+ if (toSource && id && !this.isEmptyModel) {
216
+ const canonicalModel = CanonicalModelCache.getOrInsert(CanonicalModel, id);
217
+ canonicalModel.set(toSource({ ...this.attributes, ...attrs }, canonicalModel.toJSON()), this, options);
218
+ }
219
+ }
220
+ }
169
221
  }
170
222
  Object.assign(Model.prototype, Events);
@@ -17,6 +17,7 @@ export declare const getFromCache: (key: string) => Model<Record<string, any>, R
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
21
  }> | undefined;
21
22
  export declare const existsInCache: (key: string) => boolean;
22
23
  declare const _default: (key: string, Model: {
@@ -221,7 +221,7 @@ function getResourcePropertyName(baseName, resourceKey) {
221
221
  }
222
222
  function getEmptyModel({ resourceKey, data, options, path }) {
223
223
  const Model_ = typeof ModelMap[resourceKey] === "function" ? ModelMap[resourceKey] : Model;
224
- const emptyInstance = new Model_(data, { ...options, ...path });
224
+ const emptyInstance = new Model_(data, { ...options, ...path, subscribe: false });
225
225
  emptyInstance.isEmptyModel = true;
226
226
  Object.freeze(emptyInstance.attributes);
227
227
  Object.freeze(emptyInstance.models);
package/build/lib/sync.js CHANGED
@@ -14,7 +14,7 @@ export default function (model, options = {}) {
14
14
  });
15
15
  }
16
16
  export function ajax(options) {
17
- const hasParams = !!Object.keys(options.params).length;
17
+ const hasParams = options.params instanceof FormData || !!Object.keys(options.params).length;
18
18
  const hasBodyContent = !/^(?:GET|HEAD)$/.test(options.method || "") && hasParams;
19
19
  const startTime = Date.now();
20
20
  const onRequestComplete = (json, response) => {
@@ -42,7 +42,8 @@ export function ajax(options) {
42
42
  },
43
43
  ...(hasBodyContent ?
44
44
  {
45
- body: typeof options.params === "string" ? options.params
45
+ body: typeof options.params === "string" || options.params instanceof FormData ?
46
+ options.params
46
47
  : options.contentType === MIME_TYPE_JSON ? JSON.stringify(options.params)
47
48
  : ResourcesConfig.stringify(options.params, options),
48
49
  }
@@ -61,3 +61,6 @@ export type UseResourcesResponse = {
61
61
  [key: string]: any;
62
62
  }): void;
63
63
  };
64
+ export type NestedKeys<T, Depth extends number = 3> = Depth extends 0 ? never : T extends Record<string, any> ? {
65
+ [K in Extract<keyof T, string>]: T[K] extends Record<string, any> | undefined ? `${K}` | `${K}.${NestedKeys<Exclude<T[K], undefined>, Depth extends 1 ? 0 : Depth extends 2 ? 1 : Depth extends 3 ? 2 : never>}` : `${K}`;
66
+ }[Extract<keyof T, string>] : never;
@@ -12,3 +12,4 @@ export declare function urlError(): void;
12
12
  export declare function isDeepEqual(obj1: Record<string, any>, obj2: Record<string, any>): boolean;
13
13
  export declare function sortBy(list: any[] | undefined, comparator: (val: any) => string | number): any[];
14
14
  export declare function result(obj: Record<string, any> | undefined, prop: string, ...args: any[]): any;
15
+ export declare function getNestedValue(obj: Record<string, any>, path: string): any;
@@ -86,3 +86,6 @@ export function sortBy(list = [], comparator) {
86
86
  export function result(obj = {}, prop, ...args) {
87
87
  return typeof obj[prop] === "function" ? obj[prop](...args) : obj[prop];
88
88
  }
89
+ export function getNestedValue(obj, path) {
90
+ return path.split(".").reduce((acc, key) => acc?.[key], obj);
91
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "resourcerer",
3
- "version": "2.0.6",
3
+ "version": "2.1.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "github.com/noahgrant/resourcerer"
@@ -0,0 +1,75 @@
1
+ import CanonicalModelCache from "../lib/canonical-model-cache";
2
+ import CanonicalModel from "../lib/canonical-model";
3
+ import { beforeEach, vi } from "vitest";
4
+
5
+ class CanonicalTestModel extends CanonicalModel {}
6
+
7
+ describe("CanonicalModelCache", () => {
8
+ beforeEach(() => {
9
+ vi.spyOn(CanonicalModelCache, "set");
10
+ CanonicalModelCache.remove(CanonicalTestModel, "1234");
11
+ });
12
+
13
+ afterEach(() => {
14
+ vi.restoreAllMocks();
15
+ });
16
+
17
+ describe("getOrInsert", () => {
18
+ it("returns the canonical model for the given id", () => {
19
+ const testModel = new CanonicalTestModel();
20
+
21
+ CanonicalModelCache.set(CanonicalTestModel, "1234", testModel);
22
+ CanonicalModelCache.set.mockClear();
23
+
24
+ const canonicalModel = CanonicalModelCache.getOrInsert(CanonicalTestModel, "1234");
25
+
26
+ expect(canonicalModel).toBeDefined();
27
+ expect(canonicalModel).toEqual(testModel);
28
+ expect(CanonicalModelCache.set).not.toHaveBeenCalled();
29
+ });
30
+
31
+ it("creates a new canonical model if one doesn't exist", () => {
32
+ const canonicalModel = CanonicalModelCache.getOrInsert(CanonicalTestModel, "1234");
33
+
34
+ expect(canonicalModel).toBeDefined();
35
+ expect(CanonicalModelCache.set).toHaveBeenCalledWith(
36
+ CanonicalTestModel,
37
+ "1234",
38
+ canonicalModel,
39
+ );
40
+ });
41
+ });
42
+
43
+ describe("set", () => {
44
+ it("adds a canonical model to the cache at its id and model class", () => {
45
+ const canonicalModel = new CanonicalTestModel();
46
+ const canonicalModel2 = new CanonicalTestModel();
47
+
48
+ CanonicalModelCache.set(CanonicalTestModel, "1234", canonicalModel);
49
+ CanonicalModelCache.set(CanonicalTestModel, "1235", canonicalModel2);
50
+ expect(CanonicalModelCache.getOrInsert(CanonicalTestModel, "1234")).toEqual(canonicalModel);
51
+ expect(CanonicalModelCache.getOrInsert(CanonicalTestModel, "1235")).toEqual(canonicalModel2);
52
+
53
+ CanonicalModelCache.remove(CanonicalTestModel, "1235");
54
+ });
55
+
56
+ it("creates a new map for the model class if one doesn't exist", () => {
57
+ const canonicalModel = new CanonicalTestModel();
58
+
59
+ CanonicalModelCache.set(CanonicalTestModel, "1234", canonicalModel);
60
+ expect(CanonicalModelCache.getOrInsert(CanonicalTestModel, "1234")).toEqual(canonicalModel);
61
+ });
62
+ });
63
+
64
+ describe("remove", () => {
65
+ it("removes a canonical model from the cache", () => {
66
+ const canonicalModel = new CanonicalTestModel();
67
+
68
+ vi.spyOn(Map.prototype, "delete");
69
+ CanonicalModelCache.set(CanonicalTestModel, "1234", canonicalModel);
70
+ CanonicalModelCache.remove(CanonicalTestModel, "1234");
71
+
72
+ expect(Map.prototype.delete).toHaveBeenCalledWith("1234");
73
+ });
74
+ });
75
+ });
@@ -0,0 +1,87 @@
1
+ import CanonicalModelCache from "../lib/canonical-model-cache";
2
+ import Model from "../lib/model";
3
+ import { vi } from "vitest";
4
+ import CanonicalModel from "../lib/canonical-model";
5
+
6
+ class CanonicalTestModel extends CanonicalModel {}
7
+
8
+ describe("CanonicalModel", () => {
9
+ let model;
10
+ let context = {};
11
+ const callback = vi.fn();
12
+
13
+ afterEach(() => {
14
+ callback.mockClear();
15
+ });
16
+
17
+ describe("get", () => {
18
+ it("returns the attribute value", () => {
19
+ model = new CanonicalTestModel();
20
+ model.set({ one: "one" });
21
+ expect(model.get("one")).toEqual("one");
22
+ });
23
+ });
24
+
25
+ describe("set", () => {
26
+ describe("triggers an update", () => {
27
+ beforeEach(() => {
28
+ model = new CanonicalTestModel();
29
+ model.onUpdate(callback);
30
+ });
31
+
32
+ it("if a value has changed", () => {
33
+ model.set({ one: "one" }, context);
34
+ expect(callback).toHaveBeenCalledWith(model.toJSON(), context);
35
+ callback.mockClear();
36
+
37
+ model.set({ two: { three: "four" } }, context);
38
+ expect(callback).toHaveBeenCalledWith(model.toJSON(), context);
39
+ callback.mockClear();
40
+
41
+ model.set({ one: "one" });
42
+ expect(callback).not.toHaveBeenCalled();
43
+
44
+ model.set();
45
+ expect(callback).not.toHaveBeenCalled();
46
+
47
+ model.set({ one: null }, context, { unset: true });
48
+ expect(model.toJSON()).toEqual({ two: { three: "four" } });
49
+ expect(callback).toHaveBeenCalledWith(model.toJSON(), context);
50
+ });
51
+ });
52
+ });
53
+
54
+ describe("removeSubscription", () => {
55
+ const subscriberModel = new Model();
56
+
57
+ beforeEach(() => {
58
+ model = new CanonicalTestModel();
59
+ model.onUpdate(callback, subscriberModel);
60
+ });
61
+
62
+ it("removes the subscription from the canonical model", () => {
63
+ model.removeSubscription(subscriberModel, "1234");
64
+ model.set({ one: "one" }, subscriberModel);
65
+ expect(callback).not.toHaveBeenCalled();
66
+ });
67
+
68
+ it("removes the canonical model from the cache if there are no more subscriptions", () => {
69
+ vi.spyOn(CanonicalModelCache, "remove").mockReturnValue();
70
+
71
+ model.removeSubscription(subscriberModel, "1234");
72
+ expect(CanonicalModelCache.remove).toHaveBeenCalledWith(CanonicalTestModel, "1234");
73
+ });
74
+ });
75
+
76
+ describe("toJSON", () => {
77
+ it("returns a copy of the attributes", () => {
78
+ model = new CanonicalTestModel();
79
+ model.set({ one: "one" });
80
+
81
+ const json = model.toJSON();
82
+
83
+ json.one = "two";
84
+ expect(model.toJSON()).toEqual({ one: "one" });
85
+ });
86
+ });
87
+ });
@@ -9,12 +9,13 @@ describe("Collection", () => {
9
9
 
10
10
  beforeEach(() => {
11
11
  vi.spyOn(sync, "default").mockResolvedValue([]);
12
+ vi.spyOn(Model.prototype, "unsubscribe");
12
13
  });
13
14
 
14
15
  afterEach(() => {
15
16
  collection = null;
16
- sync.default.mockRestore();
17
17
  callback.mockClear();
18
+ vi.restoreAllMocks();
18
19
  });
19
20
 
20
21
  it("is instantiated with appropriate internal properties", () => {
@@ -113,6 +114,7 @@ describe("Collection", () => {
113
114
  expect(collection.length).toEqual(3);
114
115
 
115
116
  collection.remove({ id: "model2" });
117
+ expect(Model.prototype.unsubscribe).toHaveBeenCalledTimes(1);
116
118
  expect(collection.toJSON()).toEqual([{ id: "model1" }, { id: "model3" }]);
117
119
  expect(collection.length).toEqual(2);
118
120
  expect(collection.get("model2")).not.toBeDefined();
@@ -120,6 +122,8 @@ describe("Collection", () => {
120
122
  collection.remove([{ id: "model1" }, { id: "model3" }]);
121
123
  expect(collection.toJSON()).toEqual([]);
122
124
  expect(collection.length).toEqual(0);
125
+
126
+ expect(Model.prototype.unsubscribe).toHaveBeenCalledTimes(3);
123
127
  });
124
128
 
125
129
  it("does not trigger an update if the `silent` flag is passed", () => {
@@ -132,6 +136,7 @@ describe("Collection", () => {
132
136
 
133
137
  collection.remove({ id: "model1" }, { silent: true });
134
138
  expect(callback).not.toHaveBeenCalled();
139
+ expect(Model.prototype.unsubscribe).toHaveBeenCalledTimes(2);
135
140
  });
136
141
 
137
142
  it("does not trigger an update if nothing was removed", () => {
@@ -308,7 +313,7 @@ describe("Collection", () => {
308
313
  { id: "model1", name: "noah" },
309
314
  { id: "model2", name: "zorah" },
310
315
  ],
311
- { comparator: "name" }
316
+ { comparator: "name" },
312
317
  );
313
318
 
314
319
  collection.set({ id: "model3", name: "alex" });
@@ -655,6 +660,15 @@ describe("Collection", () => {
655
660
  });
656
661
  });
657
662
 
663
+ describe("unsubscribe", () => {
664
+ it("unsubscribes all models in the collection", () => {
665
+ collection = new Collection([{ id: "model1" }, { id: "model2" }, { id: "model3" }]);
666
+ collection.unsubscribe();
667
+ expect(Model.prototype.unsubscribe).toHaveBeenCalledTimes(3);
668
+ expect(collection).toHaveLength(3);
669
+ });
670
+ });
671
+
658
672
  describe("_updateModelReference", () => {
659
673
  it("updates the reference to a model when its id changes", () => {
660
674
  var model = new Model({ id: "model1" });