-
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathEntityMixin.ts
More file actions
491 lines (451 loc) · 14.5 KB
/
EntityMixin.ts
File metadata and controls
491 lines (451 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import type {
Schema,
Visit,
IQueryDelegate,
INormalizeDelegate,
} from '../interface.js';
import { AbstractInstanceType } from '../normal.js';
import type {
IEntityClass,
IEntityInstance,
EntityOptions,
RequiredPKOptions,
IDClass,
Constructor,
PKClass,
} from './EntityTypes.js';
/**
* Turns any class into an Entity.
* @see https://dataclient.io/rest/api/EntityMixin
*/
export default function EntityMixin<TBase extends PKClass>(
Base: TBase,
opt?: EntityOptions<InstanceType<TBase>>,
): IEntityClass<TBase> & TBase;
// id is in Instance, so we default to that as pk
export default function EntityMixin<TBase extends IDClass>(
Base: TBase,
opt?: EntityOptions<InstanceType<TBase>>,
): IEntityClass<TBase> & TBase & (new (...args: any[]) => IEntityInstance);
// pk was specified in options, so we don't need to redefine
export default function EntityMixin<TBase extends Constructor>(
Base: TBase,
opt: RequiredPKOptions<InstanceType<TBase>>,
): IEntityClass<TBase> & TBase & (new (...args: any[]) => IEntityInstance);
export default function EntityMixin<TBase extends Constructor>(
Base: TBase,
options: EntityOptions<InstanceType<TBase>> = {},
) {
/**
* Entity defines a single (globally) unique object.
* @see https://dataclient.io/rest/api/Entity
*/
abstract class EntityMixin extends Base {
static toString() {
return this.key;
}
static toJSON() {
return {
key: this.key,
schema: this.schema,
};
}
/** Defines nested entities */
declare static schema: { [k: string]: Schema };
/**
* A unique identifier for each Entity
*
* @see https://dataclient.io/rest/api/Entity#pk
* @param [parent] When normalizing, the object which included the entity
* @param [key] When normalizing, the key where this entity was found
* @param [args] ...args sent to Endpoint
*/
declare pk: (
parent?: any,
key?: string,
args?: readonly any[],
) => string | number | undefined;
/** Returns the globally unique identifier for the static Entity */
declare static key: string;
// default implementation in class static block at bottom of definition
/** Defines indexes to enable lookup by */
declare static indexes?: readonly string[];
/**
* A unique identifier for each Entity
*
* @see https://dataclient.io/rest/api/Entity#pk
* @param [value] POJO of the entity or subset used
* @param [parent] When normalizing, the object which included the entity
* @param [key] When normalizing, the key where this entity was found
* @param [args] ...args sent to Endpoint
*/
static pk<T extends typeof EntityMixin>(
this: T,
value: Partial<AbstractInstanceType<T>>,
parent?: any,
key?: string,
args?: readonly any[],
): string | number | undefined {
return this.prototype.pk.call(value, parent, key, args);
}
/** Return true to merge incoming data; false keeps existing entity
*
* @see https://dataclient.io/rest/api/Entity#shouldUpdate
*/
static shouldUpdate(
existingMeta: { date: number; fetchedAt: number },
incomingMeta: { date: number; fetchedAt: number },
existing: any,
incoming: any,
) {
return true;
}
/** Determines the order of incoming entity vs entity already in store\
*
* @see https://dataclient.io/rest/api/Entity#shouldReorder
* @returns true if incoming entity should be first argument of merge()
*/
static shouldReorder(
existingMeta: { date: number; fetchedAt: number },
incomingMeta: { date: number; fetchedAt: number },
existing: any,
incoming: any,
) {
return incomingMeta.fetchedAt < existingMeta.fetchedAt;
}
/** Creates new instance copying over defined values of arguments
*
* @see https://dataclient.io/rest/api/Entity#merge
*/
static merge(existing: any, incoming: any) {
return {
...existing,
...incoming,
};
}
/** Run when an existing entity is found in the store
*
* @see https://dataclient.io/rest/api/Entity#mergeWithStore
*/
static mergeWithStore(
existingMeta: {
date: number;
fetchedAt: number;
},
incomingMeta: { date: number; fetchedAt: number },
existing: any,
incoming: any,
) {
const shouldUpdate = this.shouldUpdate(
existingMeta,
incomingMeta,
existing,
incoming,
);
if (shouldUpdate) {
// distinct types are not mergeable (like delete symbol), so just replace
if (typeof incoming !== typeof existing) {
return incoming;
} else {
return (
this.shouldReorder(existingMeta, incomingMeta, existing, incoming)
) ?
this.merge(incoming, existing)
: this.merge(existing, incoming);
}
} else {
return existing;
}
}
/** Run when an existing entity is found in the store
*
* @see https://dataclient.io/rest/api/Entity#mergeMetaWithStore
*/
static mergeMetaWithStore(
existingMeta: {
fetchedAt: number;
date: number;
expiresAt: number;
},
incomingMeta: { fetchedAt: number; date: number; expiresAt: number },
existing: any,
incoming: any,
) {
return (
this.shouldReorder(existingMeta, incomingMeta, existing, incoming)
) ?
existingMeta
: incomingMeta;
}
/** Factory method to convert from Plain JS Objects.
*
* @param [props] Plain Object of properties to assign.
*/
static fromJS<T extends typeof EntityMixin>(
this: T,
// TODO: this should only accept members that are not functions
props: Partial<AbstractInstanceType<T>> = {},
): AbstractInstanceType<T> {
// we type guarded abstract case above, so ok to force typescript to allow constructor call
const instance = new (this as any)(props) as AbstractInstanceType<T>;
// we can't rely on constructors and override the defaults provided as property assignments
// all occur after the constructor
Object.assign(instance, props);
return instance;
}
/** Called when denormalizing an entity to create an instance when 'valid'
*
* @see https://dataclient.io/rest/api/Entity#createIfValid
* @param [props] Plain Object of properties to assign.
*/
static createIfValid<T extends typeof EntityMixin>(
this: T,
// TODO: this should only accept members that are not functions
props: Partial<AbstractInstanceType<T>>,
): AbstractInstanceType<T> | undefined {
if (this.validate(props)) {
return undefined as any;
}
return this.fromJS(props);
}
/** Do any transformations when first receiving input
*
* @see https://dataclient.io/rest/api/Entity#process
*/
static process(
input: any,
parent: any,
key: string | undefined,
args: any,
): any {
return { ...input };
}
static normalize(
input: any,
parent: any,
key: string | undefined,
args: readonly any[],
visit: Visit,
delegate: INormalizeDelegate,
): any {
const processedEntity = this.process(input, parent, key, args);
let id: string | number | undefined;
if (typeof processedEntity === 'undefined') {
id = `${this.pk(input, parent, key, args)}`;
// TODO: add undefined id check
delegate.invalidate(this, id);
return id;
}
id = this.pk(processedEntity, parent, key, args);
if (id === undefined || id === '' || id === 'undefined') {
// 'creates' conceptually should allow missing PK to make optimistic creates easy
if (process.env.NODE_ENV !== 'production' && !visit.creating) {
let why: string;
if (
!('pk' in options) &&
EntityMixin.prototype.pk === this.prototype.pk &&
!('id' in processedEntity)
) {
why = `'id' missing but needed for default pk(). Try defining pk() for your Entity.`;
} else {
why = `This is likely due to a malformed response.
Try inspecting the network response or fetch() return value.
Or use debugging tools: https://dataclient.io/docs/getting-started/debugging`;
}
const error = new Error(
`Missing usable primary key when normalizing response.
${why}
Learn more about primary keys: https://dataclient.io/rest/api/Entity#pk
Entity: ${this.key}
Value (processed): ${
processedEntity && JSON.stringify(processedEntity, null, 2)
}
`,
);
(error as any).status = 400;
throw error;
}
// create a random id if a valid one cannot be computed
// this is useful for optimistic creates that don't need real ids - just something to hold their place
id = `MISS-${Math.random()}`;
} else {
id = `${id}`;
}
/* Circular reference short-circuiter */
if (delegate.checkLoop(this.key, id, input)) return id;
const errorMessage = this.validate(processedEntity);
throwValidationError(errorMessage);
Object.keys(this.schema).forEach(key => {
if (Object.hasOwn(processedEntity, key)) {
processedEntity[key] = visit(
this.schema[key],
processedEntity[key],
processedEntity,
key,
args,
);
}
});
delegate.mergeEntity(this, id, processedEntity);
return id;
}
static validate(processedEntity: any): string | undefined {
return;
}
static queryKey(
args: readonly any[],
unvisit: any,
delegate: IQueryDelegate,
): any {
if (!args[0]) return;
const id = queryKeyCandidate(this, args, delegate);
// ensure this actually has entity or we shouldn't try to use it in our query
if (id && delegate.getEntity(this.key, id)) return id;
}
static denormalize<T extends typeof EntityMixin>(
this: T,
input: any,
args: any[],
unvisit: (schema: any, input: any) => any,
): AbstractInstanceType<T> {
if (typeof input === 'symbol') {
return input as any;
}
// note: iteration order must be stable
for (const key of Object.keys(this.schema)) {
const schema = this.schema[key];
const value = unvisit(schema, input[key]);
if (typeof value === 'symbol') {
// if default is not 'falsy', then this is required, so propagate INVALID symbol
if (this.defaults[key]) {
return value as any;
}
input[key] = undefined;
} else {
input[key] = value;
}
}
return input;
}
/** All instance defaults set */
static get defaults() {
// we use hasOwn because we don't want to use a parents' defaults
if (!Object.hasOwn(this, '__defaults'))
Object.defineProperty(this, '__defaults', {
value: new (this as any)(),
writable: true,
configurable: true,
});
return (this as any).__defaults;
}
}
const { pk, schema, key, ...staticProps } = options;
// remaining options
Object.assign(EntityMixin, staticProps);
if ('schema' in options) {
EntityMixin.schema = options.schema as any;
} else if (!(Base as any).schema) {
EntityMixin.schema = {};
}
if ('pk' in options) {
if (typeof options.pk === 'function') {
EntityMixin.prototype.pk = function (parent?: any, key?: string) {
return (options.pk as any)(this, parent, key);
};
} else {
EntityMixin.prototype.pk = function () {
return (this as any)[options.pk];
};
}
// default to 'id' field if the base class doesn't have a pk
} else if (typeof Base.prototype.pk !== 'function') {
EntityMixin.prototype.pk = function () {
return (this as any).id;
};
}
if ('key' in options) {
Object.defineProperty(EntityMixin, 'key', {
value: options.key,
configurable: true,
writable: true,
enumerable: true,
});
} else if (!('key' in Base)) {
function set(this: any, value: string) {
Object.defineProperty(this, 'key', {
value,
writable: true,
enumerable: true,
configurable: true,
});
}
const baseGet = function (this: { name: string }): string {
const name = this.name === 'EntityMixin' ? Base.name : this.name;
/* istanbul ignore next */
if (
process.env.NODE_ENV !== 'production' &&
(name === '' || name === 'EntityMixin' || name === '_temp')
)
throw new Error(
'Entity classes without a name must define `static key`\nSee: https://dataclient.io/rest/api/Entity#key',
);
return name;
};
const get =
/* istanbul ignore if */
typeof document !== 'undefined' && (document as any).CLS_MANGLE ?
/* istanbul ignore next */ function (this: {
name: string;
key: string;
}): string {
(document as any).CLS_MANGLE?.(this);
Object.defineProperty(EntityMixin, 'key', {
get: baseGet,
set,
enumerable: true,
configurable: true,
});
return baseGet.call(this);
}
: baseGet;
Object.defineProperty(EntityMixin, 'key', {
get,
set,
enumerable: true,
configurable: true,
});
}
return EntityMixin as any;
}
function indexFromParams<I extends string>(
params: Readonly<object>,
indexes?: Readonly<I[]>,
) {
if (!indexes) return undefined;
return indexes.find(index => Object.hasOwn(params, index));
}
// part of the reason for pulling this out is that all functions that throw are deoptimized
function throwValidationError(errorMessage: string | undefined) {
if (errorMessage) {
const error = new Error(errorMessage);
(error as any).status = 400;
throw error;
}
}
function queryKeyCandidate(
schema: any,
args: readonly any[],
delegate: IQueryDelegate,
) {
if (['string', 'number'].includes(typeof args[0])) {
return `${args[0]}`;
}
const id = schema.pk(args[0], undefined, '', args);
// Was able to infer the entity's primary key from params
if (id !== undefined && id !== '') return id;
// now attempt lookup in indexes
const indexName = indexFromParams(args[0], schema.indexes);
if (!indexName) return;
const value = (args[0] as Record<string, any>)[indexName];
return delegate.getIndex(schema.key, indexName, value);
}