resourcerer 2.0.7 → 2.1.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/build/index.d.ts +2 -1
- package/build/index.js +1 -0
- package/build/lib/canonical-model-cache.d.ts +8 -0
- package/build/lib/canonical-model-cache.js +24 -0
- package/build/lib/canonical-model.d.ts +14 -0
- package/build/lib/canonical-model.js +33 -0
- package/build/lib/collection.d.ts +4 -2
- package/build/lib/collection.js +11 -4
- package/build/lib/events.d.ts +7 -7
- package/build/lib/events.js +2 -2
- package/build/lib/model-cache.d.ts +1 -0
- package/build/lib/model-cache.js +1 -0
- package/build/lib/model.d.ts +16 -3
- package/build/lib/model.js +55 -3
- package/build/lib/request.d.ts +1 -0
- package/build/lib/resourcerer.js +1 -1
- package/build/lib/types.d.ts +3 -0
- package/build/lib/utils.d.ts +1 -0
- package/build/lib/utils.js +3 -0
- package/package.json +1 -1
- package/test/canonical-model-cache.test.js +75 -0
- package/test/canonical-model.test.js +87 -0
- package/test/collection.test.js +16 -2
- package/test/events.test.js +115 -0
- package/test/model-cache.test.js +30 -24
- package/test/model.test.js +358 -1
- package/test/utils.test.js +22 -5
package/build/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { default as Collection } from "./lib/collection.js";
|
|
2
|
-
export { default as
|
|
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);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import Events from "./events.js";
|
|
2
|
-
import Model, { type ConstructorOptions, type SetOptions } from "./model.js";
|
|
2
|
+
import Model, { type CanonicalModelSubscription, type ConstructorOptions, type SetOptions } from "./model.js";
|
|
3
3
|
import sync, { type SyncOptions } from "./sync.js";
|
|
4
4
|
import { ResourceConfigObj } from "./types.js";
|
|
5
5
|
type CSetOptions = {
|
|
@@ -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);
|
|
@@ -26,6 +26,7 @@ export default class Collection<T extends Record<string, any> = object, O extend
|
|
|
26
26
|
urlOptions: Record<string, any>;
|
|
27
27
|
static Model: new (...args: any[]) => Model;
|
|
28
28
|
static idAttribute: string;
|
|
29
|
+
static subscriptions: CanonicalModelSubscription[];
|
|
29
30
|
static dependencies: Array<string | ((attrs: Record<string, any>) => Record<string, any>)>;
|
|
30
31
|
static cacheTimeout: number;
|
|
31
32
|
static comparator: comparator;
|
|
@@ -52,6 +53,7 @@ export default class Collection<T extends Record<string, any> = object, O extend
|
|
|
52
53
|
wait?: boolean;
|
|
53
54
|
} & SyncOptions & CSetOptions): Promise<[InstanceType<this["Model"]>, Response]>;
|
|
54
55
|
parse(response: any, options: SyncOptions & CSetOptions): T[];
|
|
56
|
+
unsubscribe(): void;
|
|
55
57
|
_getModelClass<T extends Record<string, any>, O extends Record<string, any>>(): typeof Model<T, O>;
|
|
56
58
|
_reset(): void;
|
|
57
59
|
_prepareModel(attrs: ModelArg<T, O>, options?: CSetOptions): Model<T, O>;
|
package/build/lib/collection.js
CHANGED
|
@@ -26,6 +26,7 @@ export default class Collection extends Events {
|
|
|
26
26
|
urlOptions = {};
|
|
27
27
|
static Model = Model;
|
|
28
28
|
static idAttribute;
|
|
29
|
+
static subscriptions = [];
|
|
29
30
|
static dependencies = [];
|
|
30
31
|
static cacheTimeout;
|
|
31
32
|
static comparator;
|
|
@@ -180,14 +181,19 @@ export default class Collection extends Events {
|
|
|
180
181
|
parse(response, options) {
|
|
181
182
|
return response;
|
|
182
183
|
}
|
|
184
|
+
unsubscribe() {
|
|
185
|
+
this.models.forEach((model) => model.unsubscribe());
|
|
186
|
+
}
|
|
183
187
|
_getModelClass() {
|
|
184
|
-
|
|
185
|
-
|
|
188
|
+
const { idAttribute, subscriptions } = this.constructor;
|
|
189
|
+
const DefaultModel = this.constructor.Model;
|
|
190
|
+
if (idAttribute || subscriptions.length) {
|
|
186
191
|
return class extends Model {
|
|
187
|
-
static idAttribute =
|
|
192
|
+
static idAttribute = idAttribute || DefaultModel.idAttribute;
|
|
193
|
+
static subscriptions = subscriptions;
|
|
188
194
|
};
|
|
189
195
|
}
|
|
190
|
-
return
|
|
196
|
+
return DefaultModel;
|
|
191
197
|
}
|
|
192
198
|
_reset() {
|
|
193
199
|
this.length = 0;
|
|
@@ -241,6 +247,7 @@ export default class Collection extends Events {
|
|
|
241
247
|
}
|
|
242
248
|
delete model.collection;
|
|
243
249
|
model.offUpdate(this);
|
|
250
|
+
model.unsubscribe();
|
|
244
251
|
}
|
|
245
252
|
_updateModelReference(id, prevId, model) {
|
|
246
253
|
if (id) {
|
package/build/lib/events.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
type CallbackEntry = {
|
|
2
|
-
callback: (...args:
|
|
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 {};
|
package/build/lib/events.js
CHANGED
|
@@ -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;
|
package/build/lib/model-cache.js
CHANGED
|
@@ -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);
|
package/build/lib/model.d.ts
CHANGED
|
@@ -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
|
|
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
|
}
|
package/build/lib/model.js
CHANGED
|
@@ -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
|
-
|
|
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() ?
|
|
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 });
|
|
@@ -143,6 +156,7 @@ export default class Model extends Events {
|
|
|
143
156
|
this.triggerUpdate();
|
|
144
157
|
this.collection?.remove(this, { silent: true });
|
|
145
158
|
}
|
|
159
|
+
this.unsubscribe();
|
|
146
160
|
return [this, response];
|
|
147
161
|
})
|
|
148
162
|
.catch((response) => {
|
|
@@ -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);
|
package/build/lib/request.d.ts
CHANGED
|
@@ -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: {
|
package/build/lib/resourcerer.js
CHANGED
|
@@ -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/types.d.ts
CHANGED
|
@@ -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;
|
package/build/lib/utils.d.ts
CHANGED
|
@@ -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;
|
package/build/lib/utils.js
CHANGED
|
@@ -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
|
@@ -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
|
+
});
|