resourcerer 1.2.3 → 2.0.0-beta-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.
Files changed (59) hide show
  1. package/README.md +133 -164
  2. package/build/index.d.ts +9 -0
  3. package/build/index.js +9 -0
  4. package/build/lib/collection.d.ts +107 -0
  5. package/build/lib/collection.js +251 -0
  6. package/build/lib/config.d.ts +20 -0
  7. package/build/lib/config.js +23 -0
  8. package/build/lib/error-boundary.d.ts +12 -0
  9. package/build/lib/error-boundary.js +18 -0
  10. package/build/lib/events.d.ts +11 -0
  11. package/build/lib/events.js +12 -0
  12. package/build/lib/model-cache.d.ts +13 -0
  13. package/build/lib/model-cache.js +62 -0
  14. package/build/lib/model.d.ts +48 -0
  15. package/build/lib/model.js +170 -0
  16. package/build/lib/prefetch.d.ts +3 -0
  17. package/build/lib/prefetch.js +27 -0
  18. package/build/lib/request.d.ts +20 -0
  19. package/build/lib/request.js +53 -0
  20. package/build/lib/resourcerer.d.ts +13 -0
  21. package/build/lib/resourcerer.js +406 -0
  22. package/build/lib/sync.d.ts +18 -0
  23. package/build/lib/sync.js +58 -0
  24. package/build/lib/types.d.ts +66 -0
  25. package/build/lib/types.js +1 -0
  26. package/build/lib/utils.d.ts +14 -0
  27. package/build/lib/utils.js +87 -0
  28. package/docs/advanced_topics.md +9 -77
  29. package/docs/collection.md +28 -28
  30. package/docs/migrating_to_2.0.md +72 -0
  31. package/docs/model.md +21 -21
  32. package/docs/typescript.md +72 -22
  33. package/package.json +27 -30
  34. package/resourcerer.d.ts +58 -0
  35. package/test/collection.test.js +305 -316
  36. package/test/config.test.js +21 -75
  37. package/test/events.test.js +42 -41
  38. package/test/model-cache.test.js +99 -77
  39. package/test/model.test.js +204 -209
  40. package/test/prefetch.test.js +35 -61
  41. package/test/request.test.js +104 -109
  42. package/test/sync.test.js +122 -109
  43. package/test/utils.test.js +173 -159
  44. package/index.d.ts +0 -270
  45. package/index.js +0 -14
  46. package/lib/collection.js +0 -584
  47. package/lib/config.js +0 -131
  48. package/lib/constants.js +0 -6
  49. package/lib/error-boundary.js +0 -47
  50. package/lib/events.js +0 -19
  51. package/lib/model-cache.js +0 -131
  52. package/lib/model.js +0 -372
  53. package/lib/prefetch.js +0 -59
  54. package/lib/request.js +0 -126
  55. package/lib/resourcerer.js +0 -985
  56. package/lib/sync.js +0 -111
  57. package/lib/utils.js +0 -220
  58. package/test/model-mocks.js +0 -110
  59. package/test/setup.js +0 -63
@@ -0,0 +1,9 @@
1
+ export { default as Collection } from "./lib/collection.js";
2
+ export { default as Model } from "./lib/model.js";
3
+ export { default as sync, ajax, type SyncOptions } from "./lib/sync.js";
4
+ export { default as prefetch } from "./lib/prefetch.js";
5
+ export { default as request } from "./lib/request.js";
6
+ export { default as ModelCache } from "./lib/model-cache.js";
7
+ export * as Utils from "./lib/utils.js";
8
+ export { register, ModelMap, ResourcesConfig } from "./lib/config.js";
9
+ export { useResources, withResources } from "./lib/resourcerer.js";
package/build/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { default as Collection } from "./lib/collection.js";
2
+ export { default as Model } from "./lib/model.js";
3
+ export { default as sync, ajax } from "./lib/sync.js";
4
+ export { default as prefetch } from "./lib/prefetch.js";
5
+ export { default as request } from "./lib/request.js";
6
+ export { default as ModelCache } from "./lib/model-cache.js";
7
+ export * as Utils from "./lib/utils.js";
8
+ export { register, ModelMap, ResourcesConfig } from "./lib/config.js";
9
+ export { useResources, withResources } from "./lib/resourcerer.js";
@@ -0,0 +1,107 @@
1
+ import Events from "./events.js";
2
+ import Model, { type ConstructorOptions, type SetOptions } from "./model.js";
3
+ import sync, { type SyncOptions } from "./sync.js";
4
+ import { ResourceConfigObj } from "./types.js";
5
+ type CSetOptions = {
6
+ parse?: boolean;
7
+ silent?: boolean;
8
+ [key: string]: any;
9
+ } & SetOptions & ConstructorOptions;
10
+ type ModelArg<A extends Record<string, any>, O extends Record<string, any>> = Model<A, O> | Record<string, any>;
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> extends Events {
13
+ lazy?: boolean;
14
+ refetching?: boolean;
15
+ measure?: boolean | ((config: ResourceConfigObj) => boolean);
16
+ isEmptyModel?: boolean;
17
+ Model: typeof Model<T, O>;
18
+ comparator?: comparator;
19
+ models: InstanceType<this["Model"]>[];
20
+ length: number;
21
+ _byId: Record<string, Model<T, O>>;
22
+ constructor(models?: ModelArg<T, O> | ModelArg<T, O>[], options?: O & {
23
+ Model?: typeof Model<T, O>;
24
+ comparator?: comparator;
25
+ } & CSetOptions);
26
+ urlOptions: Record<string, any>;
27
+ static Model: typeof Model;
28
+ static idAttribute: string;
29
+ static dependencies: Array<string | ((attrs: Record<string, any>) => Record<string, any>)>;
30
+ static cacheTimeout: number;
31
+ static comparator: comparator;
32
+ static measure: boolean | ((config: ResourceConfigObj) => boolean);
33
+ toJSON(): T[];
34
+ sync(...args: Parameters<typeof sync>): Promise<[any, Response]>;
35
+ add(models: ModelArg<T, O> | ModelArg<T, O>[], options?: CSetOptions): this;
36
+ remove(models: Model<T, O>["id"] | Model<T, O>["id"][] | ModelArg<T, O> | ModelArg<T, O>[], options?: CSetOptions): this;
37
+ set(models?: ModelArg<T, O> | ModelArg<T, O>[], options?: CSetOptions): this;
38
+ reset(models?: ModelArg<T, O> | ModelArg<T, O>[], options?: CSetOptions): this;
39
+ get(obj: Model<T, O>["id"] | ModelArg<T, O>): InstanceType<this["Model"]> | undefined;
40
+ has(obj: Model<T, O>["id"] | ModelArg<T, O>): boolean;
41
+ at(index: number): InstanceType<this["Model"]> | undefined;
42
+ map(predicate: (model: InstanceType<this["Model"]>) => any): any[];
43
+ find(predicate: (model: InstanceType<this["Model"]>) => boolean): InstanceType<this["Model"]> | undefined;
44
+ filter(predicate: (model: InstanceType<this["Model"]>) => boolean): InstanceType<this["Model"]>[];
45
+ findWhere(attrs: Partial<T>): InstanceType<this["Model"]> | undefined;
46
+ where<B extends boolean = false>(attrs: Partial<T>, first?: B): B extends true ? InstanceType<this["Model"]> | undefined : InstanceType<this["Model"]>[];
47
+ pluck<K extends keyof T>(attr: K): T[K][];
48
+ slice(...args: number[]): InstanceType<this["Model"]>[];
49
+ sort(): this;
50
+ fetch(options?: SyncOptions & CSetOptions): Promise<readonly [this, Response]>;
51
+ create(model: ModelArg<T, O>, options?: {
52
+ wait?: boolean;
53
+ } & SyncOptions & CSetOptions): Promise<[InstanceType<this["Model"]>, Response]>;
54
+ parse(response: any, options: SyncOptions & CSetOptions): T[];
55
+ _getModelClass<T extends Record<string, any>, O extends Record<string, any>>(): {
56
+ new (attributes?: T_1 | undefined, options?: O_1 & SetOptions & ConstructorOptions): {
57
+ cid: string;
58
+ id: string | number;
59
+ attributes: T_1;
60
+ readonly urlOptions: O_1;
61
+ collection?: Collection<object, object> | undefined;
62
+ lazy?: boolean | undefined;
63
+ refetching?: boolean | undefined;
64
+ measure?: boolean | ((config: ResourceConfigObj) => boolean) | undefined;
65
+ isEmptyModel?: boolean | undefined;
66
+ toJSON(): T_1;
67
+ sync(model: Collection<object, object> | Model<Record<string, any>, Record<string, any>>, options?: SyncOptions | undefined): Promise<[any, Response]>;
68
+ get<K extends keyof T_1>(attr: K): T_1[K];
69
+ pick<K_1 extends keyof T_1>(...attrs: K_1[]): Pick<T_1, K_1>;
70
+ has(attr: keyof T_1): boolean;
71
+ set(attrs?: Partial<T_1>, options?: SetOptions): any;
72
+ unset(attr: keyof T_1, options?: SetOptions | undefined): any;
73
+ clear(options: SetOptions): any;
74
+ fetch(options?: SyncOptions & SetOptions): Promise<readonly [any, Response]>;
75
+ save(attrs: Partial<T_1>, options?: {
76
+ wait?: boolean | undefined;
77
+ patch?: boolean | undefined;
78
+ } & SyncOptions & SetOptions): Promise<[any, Response]>;
79
+ destroy(options?: {
80
+ wait?: boolean | undefined;
81
+ } & SyncOptions & SetOptions): Promise<[any, Response]>;
82
+ url(options?: O_2): string;
83
+ parse(response: any, options: SyncOptions & SetOptions): T_1;
84
+ isNew(): boolean;
85
+ _callbacks: {
86
+ callback: (...args: any[]) => void;
87
+ context: {};
88
+ }[];
89
+ triggerUpdate(): void;
90
+ onUpdate(callback: (...args: any[]) => void, context: {}): void;
91
+ offUpdate(ctx: {}): void;
92
+ };
93
+ idAttribute: string;
94
+ dependencies: (string | ((attrs: Record<string, any>) => Record<string, any>))[];
95
+ cacheTimeout: number;
96
+ defaults: {};
97
+ measure: boolean | ((config: ResourceConfigObj) => boolean);
98
+ };
99
+ _reset(): void;
100
+ _prepareModel(attrs: ModelArg<T, O>, options?: CSetOptions): Model<T, O>;
101
+ _removeModels(models: (Model<T, O>["id"] | ModelArg<T, O>)[]): InstanceType<this["Model"]>[];
102
+ _isModel(model: any): boolean;
103
+ _addReference(model: Model<T, O>): void;
104
+ _removeReference(model: Model<T, O>): void;
105
+ _updateModelReference(id: string | number, prevId: string | number, model: Model<T, O>): void;
106
+ }
107
+ export {};
@@ -0,0 +1,251 @@
1
+ import { isDeepEqual, sortBy } from "./utils.js";
2
+ import Events from "./events.js";
3
+ import Model from "./model.js";
4
+ import sync from "./sync.js";
5
+ export default class Collection extends Events {
6
+ lazy;
7
+ refetching;
8
+ measure;
9
+ isEmptyModel;
10
+ Model;
11
+ comparator;
12
+ models = [];
13
+ length;
14
+ _byId;
15
+ constructor(models, options = {}) {
16
+ super();
17
+ const RESERVED_OPTION_KEYS = ["Model", "comparator", "silent", "parse"];
18
+ this.Model = options.Model || this._getModelClass();
19
+ this.comparator = options.comparator || this.constructor.comparator;
20
+ this._reset();
21
+ this.urlOptions = Object.keys(options).reduce((memo, key) => Object.assign(memo, !RESERVED_OPTION_KEYS.includes(key) ? { [key]: options[key] } : {}), {});
22
+ if (models) {
23
+ this.reset(models, { silent: true, ...options });
24
+ }
25
+ }
26
+ urlOptions = {};
27
+ static Model = Model;
28
+ static idAttribute;
29
+ static dependencies = [];
30
+ static cacheTimeout;
31
+ static comparator;
32
+ static measure = false;
33
+ toJSON() {
34
+ return this.map((model) => model.toJSON());
35
+ }
36
+ sync(...args) {
37
+ return sync.call(this, ...args);
38
+ }
39
+ add(models, options = {}) {
40
+ return this.set(models, options);
41
+ }
42
+ remove(models, options = {}) {
43
+ const removed = this._removeModels(!Array.isArray(models) ? [models] : models);
44
+ if (!options.silent && removed.length) {
45
+ this.triggerUpdate();
46
+ }
47
+ return this;
48
+ }
49
+ set(models, options = {}) {
50
+ let shouldSort = false;
51
+ if (!models) {
52
+ return this;
53
+ }
54
+ else if (options.parse && !this._isModel(models)) {
55
+ models = this.parse(models, options);
56
+ }
57
+ for (let model of Array.isArray(models) ? models : [models]) {
58
+ if (this.get(model)) {
59
+ let attrs = this._isModel(model) ? model.attributes : model;
60
+ this.get(model).set(options.parse ? this.get(model).parse(attrs, options) : attrs);
61
+ }
62
+ else {
63
+ model = this._prepareModel(model, options);
64
+ this.models.push(model);
65
+ this._addReference(model);
66
+ shouldSort = true;
67
+ }
68
+ }
69
+ this.length = this.models.length;
70
+ if (this.comparator && shouldSort) {
71
+ this.sort();
72
+ }
73
+ if (!options.silent) {
74
+ this.triggerUpdate();
75
+ }
76
+ return this;
77
+ }
78
+ reset(models = [], options = {}) {
79
+ for (let i = 0; i < this.models.length; i++) {
80
+ this._removeReference(this.models[i]);
81
+ }
82
+ this._reset();
83
+ this.add(models, { silent: true, ...options });
84
+ if (!options.silent) {
85
+ this.triggerUpdate();
86
+ }
87
+ return this;
88
+ }
89
+ get(obj) {
90
+ if (!obj && typeof obj !== "number") {
91
+ return undefined;
92
+ }
93
+ return typeof obj === "string" || typeof obj === "number" ?
94
+ this._byId[obj]
95
+ : this._byId[(this._isModel(obj) ? obj.attributes : obj)[this.Model.idAttribute]] ||
96
+ (obj.cid && this._byId[obj.cid]);
97
+ }
98
+ has(obj) {
99
+ return ![undefined, null].includes(this.get(obj));
100
+ }
101
+ at(index) {
102
+ if (index < 0) {
103
+ index += this.length;
104
+ }
105
+ return this.models[index];
106
+ }
107
+ map(predicate) {
108
+ return this.models.map(predicate);
109
+ }
110
+ find(predicate) {
111
+ return this.models.find(predicate);
112
+ }
113
+ filter(predicate) {
114
+ return this.models.filter(predicate);
115
+ }
116
+ findWhere(attrs) {
117
+ return this.where(attrs, true);
118
+ }
119
+ where(attrs, first) {
120
+ const predicate = (model) => {
121
+ for (let [attr, val] of Object.entries(attrs)) {
122
+ if (!isDeepEqual(model.get(attr), val)) {
123
+ return false;
124
+ }
125
+ }
126
+ return true;
127
+ };
128
+ if (first === true) {
129
+ return this.find(predicate);
130
+ }
131
+ return this.filter(predicate);
132
+ }
133
+ pluck(attr) {
134
+ return this.map((model) => model.get(attr));
135
+ }
136
+ slice(...args) {
137
+ return this.models.slice(...args);
138
+ }
139
+ sort() {
140
+ if (!this.comparator) {
141
+ throw new Error("Cannot sort a set without a comparator");
142
+ }
143
+ if (typeof this.comparator === "function" && this.comparator.length > 1) {
144
+ this.models.sort(this.comparator.bind(this));
145
+ }
146
+ else {
147
+ this.models = sortBy(this.models, (model) => typeof this.comparator === "function" ? this.comparator(model) : model.get(this.comparator));
148
+ }
149
+ return this;
150
+ }
151
+ fetch(options = {}) {
152
+ options = { parse: true, method: "GET", ...options };
153
+ return this.sync(this, options).then(([json, response]) => {
154
+ this.reset(json, { silent: true, ...options });
155
+ this.triggerUpdate();
156
+ return [this, response];
157
+ });
158
+ }
159
+ create(model, options = {}) {
160
+ model = this._prepareModel(model, options);
161
+ if (!options.wait) {
162
+ this.add(model, options);
163
+ }
164
+ return model
165
+ .save(null, options)
166
+ .then((...args) => {
167
+ if (options.wait) {
168
+ this.add(model, options);
169
+ }
170
+ this._addReference(model);
171
+ return args[0];
172
+ })
173
+ .catch((response) => {
174
+ if (!options.wait) {
175
+ this.remove(model);
176
+ }
177
+ return Promise.reject(response);
178
+ });
179
+ }
180
+ parse(response, options) {
181
+ return response;
182
+ }
183
+ _getModelClass() {
184
+ if (this.constructor.idAttribute) {
185
+ let attr = this.constructor.idAttribute;
186
+ return class extends Model {
187
+ static idAttribute = attr;
188
+ };
189
+ }
190
+ return this.constructor.Model;
191
+ }
192
+ _reset() {
193
+ this.length = 0;
194
+ this.models = [];
195
+ this._byId = {};
196
+ }
197
+ _prepareModel(attrs, options = {}) {
198
+ if (this._isModel(attrs)) {
199
+ if (!attrs.collection) {
200
+ attrs.collection = this;
201
+ }
202
+ return attrs;
203
+ }
204
+ return new this.Model(attrs, { ...this.urlOptions, ...options, collection: this });
205
+ }
206
+ _removeModels(models) {
207
+ const removed = [];
208
+ for (let i = 0; i < models.length; i++) {
209
+ let model = this.get(models[i]);
210
+ if (!model) {
211
+ continue;
212
+ }
213
+ let index = this.models.indexOf(model);
214
+ this.models.splice(index, 1);
215
+ this.length--;
216
+ delete this._byId[model.cid];
217
+ if (model.attributes[this.Model.idAttribute]) {
218
+ delete this._byId[model.attributes[this.Model.idAttribute]];
219
+ }
220
+ removed.push(model);
221
+ this._removeReference(model);
222
+ }
223
+ return removed;
224
+ }
225
+ _isModel(model) {
226
+ return model instanceof Model;
227
+ }
228
+ _addReference(model) {
229
+ this._byId[model.cid] = model;
230
+ let id = model.attributes[this.Model.idAttribute];
231
+ if (id || typeof id === "number") {
232
+ this._byId[id] = model;
233
+ }
234
+ model.onUpdate(this.triggerUpdate, this);
235
+ }
236
+ _removeReference(model) {
237
+ delete this._byId[model.cid];
238
+ let id = model.attributes[this.Model.idAttribute];
239
+ if (id) {
240
+ delete this._byId[id];
241
+ }
242
+ delete model.collection;
243
+ model.offUpdate(this);
244
+ }
245
+ _updateModelReference(id, prevId, model) {
246
+ if (id) {
247
+ delete this._byId[prevId];
248
+ this._byId[id] = model;
249
+ }
250
+ }
251
+ }
@@ -0,0 +1,20 @@
1
+ import { type ReactElement } from "react";
2
+ import { type SyncOptions } from "./sync.js";
3
+ import { type ModelMap as _ModelMap } from "./types.js";
4
+ export interface ResourcererConfig {
5
+ cacheGracePeriod: number;
6
+ errorBoundaryChild: ReactElement;
7
+ stringify: (params: string | URLSearchParams | string[][] | Record<string, string>, options: Record<string, any>) => string;
8
+ track: (name: string, options: {
9
+ Resource: string;
10
+ params: Record<string, any> | void;
11
+ path: Record<string, any> | void;
12
+ duration: number;
13
+ }) => void;
14
+ log: (...args: any[]) => void;
15
+ prefilter: (options: SyncOptions) => SyncOptions | void;
16
+ set: (config: Partial<ResourcererConfig>) => void;
17
+ }
18
+ export declare const register: (models: _ModelMap) => void;
19
+ export declare const ModelMap: _ModelMap;
20
+ export declare const ResourcesConfig: ResourcererConfig;
@@ -0,0 +1,23 @@
1
+ import { noOp } from "./utils.js";
2
+ import React from "react";
3
+ import { setRequestPrefilter } from "./sync.js";
4
+ export const register = (models) => {
5
+ Object.assign(ModelMap, models);
6
+ };
7
+ export const ModelMap = {};
8
+ export const ResourcesConfig = {
9
+ cacheGracePeriod: 120000,
10
+ errorBoundaryChild: React.createElement("div", { className: "caught-error" }, React.createElement("p", null, "An error occurred.")),
11
+ log: noOp,
12
+ prefilter: noOp,
13
+ stringify(params, options) {
14
+ return new URLSearchParams(params).toString();
15
+ },
16
+ track: noOp,
17
+ set(config) {
18
+ if (config.prefilter) {
19
+ setRequestPrefilter(config.prefilter);
20
+ }
21
+ return Object.assign(this, config);
22
+ },
23
+ };
@@ -0,0 +1,12 @@
1
+ import { Component, type ErrorInfo, type ReactElement } from "react";
2
+ interface ErrorBoundaryState {
3
+ caughtError: boolean;
4
+ }
5
+ export default class ErrorBoundary extends Component<{
6
+ children: ReactElement;
7
+ }, ErrorBoundaryState> {
8
+ state: ErrorBoundaryState;
9
+ componentDidCatch(err: Error, info: ErrorInfo): void;
10
+ render(): ReactElement<any, string | import("react").JSXElementConstructor<any>>;
11
+ }
12
+ export {};
@@ -0,0 +1,18 @@
1
+ import { omit } from "./utils.js";
2
+ import { Component, cloneElement } from "react";
3
+ import { ResourcesConfig } from "./config.js";
4
+ export default class ErrorBoundary extends Component {
5
+ state = {
6
+ caughtError: false,
7
+ };
8
+ componentDidCatch(err, info) {
9
+ this.setState({ caughtError: true });
10
+ ResourcesConfig.log(err, info);
11
+ }
12
+ render() {
13
+ if (this.state.caughtError) {
14
+ return ResourcesConfig.errorBoundaryChild;
15
+ }
16
+ return cloneElement(this.props.children, omit(this.props, "children"));
17
+ }
18
+ }
@@ -0,0 +1,11 @@
1
+ type CallbackEntry = {
2
+ callback: (...args: any[]) => void;
3
+ context: NonNullable<unknown>;
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;
10
+ }
11
+ export {};
@@ -0,0 +1,12 @@
1
+ export default class Events {
2
+ _callbacks = [];
3
+ triggerUpdate() {
4
+ this._callbacks?.forEach(({ callback, context }) => callback.call(context));
5
+ }
6
+ onUpdate(callback, context) {
7
+ this._callbacks = (this._callbacks || []).concat({ callback, context });
8
+ }
9
+ offUpdate(ctx) {
10
+ this._callbacks = (this._callbacks || []).filter(({ context }) => context !== ctx);
11
+ }
12
+ }
@@ -0,0 +1,13 @@
1
+ import Collection from "./collection.js";
2
+ import Model from "./model.js";
3
+ type Component = NonNullable<unknown>;
4
+ declare const _default: {
5
+ get(cacheKey: string): Collection<object, object> | Model<Record<string, any>, Record<string, any>> | undefined;
6
+ put(cacheKey: string, model: Model | Collection, component?: Component): void;
7
+ register(cacheKey: string, component?: Component): void;
8
+ unregister(component: Component, ...cacheKeys: string[]): void;
9
+ remove(cacheKey: string): void;
10
+ removeAllWithModel(resourceKey: string): void;
11
+ __removeAll__(): void;
12
+ };
13
+ export default _default;
@@ -0,0 +1,62 @@
1
+ import { ResourcesConfig } from "./config.js";
2
+ const modelCache = new Map();
3
+ const componentManifest = new Map();
4
+ const timeouts = {};
5
+ export default {
6
+ get(cacheKey) {
7
+ return modelCache.get(cacheKey);
8
+ },
9
+ put(cacheKey, model, component) {
10
+ modelCache.set(cacheKey, model);
11
+ if (component) {
12
+ this.register(cacheKey, component);
13
+ }
14
+ else {
15
+ scheduleForRemoval(cacheKey);
16
+ }
17
+ },
18
+ register(cacheKey, component) {
19
+ if (component) {
20
+ window.clearTimeout(timeouts[cacheKey]);
21
+ componentManifest.set(cacheKey, componentManifest.get(cacheKey) || new Set());
22
+ componentManifest.get(cacheKey)?.add(component);
23
+ }
24
+ },
25
+ unregister(component, ...cacheKeys) {
26
+ cacheKeys = cacheKeys.length ? cacheKeys : [...componentManifest.keys()];
27
+ for (let cacheKey of cacheKeys) {
28
+ let componentSet = componentManifest.get(cacheKey);
29
+ if (componentSet && componentSet.has(component)) {
30
+ componentSet.delete(component);
31
+ if (!componentSet.size) {
32
+ scheduleForRemoval(cacheKey);
33
+ }
34
+ }
35
+ }
36
+ },
37
+ remove(cacheKey) {
38
+ clearModel(cacheKey);
39
+ componentManifest.delete(cacheKey);
40
+ },
41
+ removeAllWithModel(resourceKey) {
42
+ for (const key of modelCache.keys()) {
43
+ if (key === resourceKey || key.startsWith(`${resourceKey}~`)) {
44
+ this.remove(key);
45
+ }
46
+ }
47
+ },
48
+ __removeAll__() {
49
+ modelCache.forEach((val, key) => clearModel(key));
50
+ componentManifest.forEach((val, key) => componentManifest.delete(key));
51
+ },
52
+ };
53
+ function scheduleForRemoval(cacheKey) {
54
+ const Constructor = modelCache.get(cacheKey)?.constructor;
55
+ const timeout = Constructor?.cacheTimeout || ResourcesConfig.cacheGracePeriod;
56
+ timeouts[cacheKey] = window.setTimeout(() => clearModel(cacheKey), timeout);
57
+ }
58
+ function clearModel(cacheKey) {
59
+ window.clearTimeout(timeouts[cacheKey]);
60
+ delete timeouts[cacheKey];
61
+ modelCache.delete(cacheKey);
62
+ }
@@ -0,0 +1,48 @@
1
+ import Events from "./events.js";
2
+ import sync, { type SyncOptions } from "./sync.js";
3
+ import Collection from "./collection.js";
4
+ import { ResourceConfigObj } from "./types.js";
5
+ export type ConstructorOptions = {
6
+ collection?: Collection;
7
+ parse?: boolean;
8
+ };
9
+ export type SetOptions = {
10
+ silent?: boolean;
11
+ unset?: boolean;
12
+ };
13
+ export default class Model<T extends Record<string, any> = Record<string, any>, O extends Record<string, any> = Record<string, any>> extends Events {
14
+ cid: string;
15
+ id: string | number;
16
+ attributes: T;
17
+ readonly urlOptions: O;
18
+ collection?: Collection;
19
+ lazy?: boolean;
20
+ refetching?: boolean;
21
+ measure?: boolean | ((config: ResourceConfigObj) => boolean);
22
+ isEmptyModel?: boolean;
23
+ constructor(attributes?: T, options?: O & SetOptions & ConstructorOptions);
24
+ static idAttribute: string;
25
+ static dependencies: Array<string | ((attrs: Record<string, any>) => Record<string, any>)>;
26
+ static cacheTimeout: number;
27
+ static defaults: {};
28
+ static measure: boolean | ((config: ResourceConfigObj) => boolean);
29
+ toJSON(): T;
30
+ sync(...args: Parameters<typeof sync>): Promise<[any, Response]>;
31
+ get<K extends keyof T>(attr: K): T[K];
32
+ pick<K extends keyof T>(...attrs: K[]): Pick<T, K>;
33
+ has(attr: keyof T): boolean;
34
+ set(attrs?: Partial<T>, options?: SetOptions): this;
35
+ unset(attr: keyof T, options?: SetOptions): this;
36
+ clear(options: SetOptions): this;
37
+ fetch(options?: SyncOptions & SetOptions): Promise<readonly [this, Response]>;
38
+ save(attrs: Partial<T>, options?: {
39
+ wait?: boolean;
40
+ patch?: boolean;
41
+ } & SyncOptions & SetOptions): Promise<[this, Response]>;
42
+ destroy(options?: {
43
+ wait?: boolean;
44
+ } & SyncOptions & SetOptions): Promise<[this, Response]>;
45
+ url(options?: O): string;
46
+ parse(response: any, options: SyncOptions & SetOptions): T;
47
+ isNew(): boolean;
48
+ }