/
mapper.ts
743 lines (621 loc) · 22.5 KB
/
mapper.ts
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
import {isOptional} from "./validation";
import * as clone from 'clone';
import * as getParameterNames from 'get-parameter-names';
import {Buffer} from 'buffer';
import {getEntitySchema} from "./decorators";
import {
ClassType,
getClassName,
getClassPropertyName,
getEnumLabels,
getEnumValues,
getValidEnumValue,
isArray,
isObject,
isUndefined,
isValidEnumValue
} from "@marcj/estdlib";
export type Types = 'objectId' | 'uuid' | 'binary' | 'class' | 'date' | 'string' | 'boolean' | 'number' | 'enum' | 'any';
const cache = new Map<Object, Map<string, any>>();
/**
* Parameter names for the constructor.
*
* @hidden
*/
export function getCachedParameterNames<T>(classType: ClassType<T>): string[] {
let valueMap = cache.get(classType.prototype);
if (!valueMap) {
valueMap = new Map();
cache.set(classType.prototype, valueMap);
}
let value = valueMap.get('parameter_names');
if (!value) {
value = getParameterNames(classType.prototype.constructor);
valueMap.set('parameter_names', value);
}
return value;
}
/**
* @hidden
*/
export interface ResolvedReflectionFound {
resolvedClassType: ClassType<any>;
resolvedPropertyName: string;
type: Types;
typeValue: any;
array: boolean;
map: boolean;
}
/**
* @hidden
*/
export type ResolvedReflection = ResolvedReflectionFound | undefined;
/**
* @hidden
*/
export function getResolvedReflection<T>(classType: ClassType<T>, propertyPath: string): ResolvedReflection {
const names = propertyPath.split('.');
let resolvedClassType: ClassType<any> = classType;
let resolvedTypeCandidate: Types | undefined;
let resolvedClassTypeCandidate: ClassType<any> | undefined = undefined;
let resolvedPropertyName: string = '';
let inArrayOrMap = false;
let inClassField = false;
let isArray = false;
let isMap = false;
for (let i = 0; i < names.length; i++) {
const name = names[i];
if (inArrayOrMap) {
if (inClassField && resolvedClassTypeCandidate) {
const {type} = getReflectionType(resolvedClassTypeCandidate, name);
if (!type) {
return;
}
inClassField = false;
inArrayOrMap = false;
resolvedClassType = resolvedClassTypeCandidate;
} else {
inClassField = true;
continue;
}
}
const {type, typeValue} = getReflectionType(resolvedClassType, name);
if (!type) {
return;
}
resolvedPropertyName = name;
isArray = isArrayType(resolvedClassType, resolvedPropertyName);
isMap = isMapType(resolvedClassType, resolvedPropertyName);
if (isArray || isMap) {
inArrayOrMap = true;
}
if (type === 'class') {
resolvedClassTypeCandidate = typeValue;
if (resolvedClassTypeCandidate) {
const decorator = getDecorator(resolvedClassTypeCandidate);
if (decorator) {
const {type, typeValue} = getReflectionType(resolvedClassTypeCandidate, decorator);
if (isArrayType(resolvedClassTypeCandidate, decorator) || isMapType(resolvedClassTypeCandidate, decorator)) {
inArrayOrMap = true;
}
if (type === 'class') {
if (!typeValue) {
throw new Error(`${getClassPropertyName(resolvedClassType, resolvedPropertyName)} has no class defined. Use Circular decorator if that class really exists.`);
}
resolvedTypeCandidate = type;
resolvedClassTypeCandidate = typeValue;
} else if (type){
if (names[i+1]) {
return {
resolvedClassType: resolvedClassType,
resolvedPropertyName: resolvedPropertyName,
type: type,
typeValue: typeValue,
array: false,
map: false,
}
} else {
return {
resolvedClassType: resolvedClassType,
resolvedPropertyName: resolvedPropertyName,
type: 'class',
typeValue: resolvedClassTypeCandidate,
array: isArray,
map: isMap,
}
}
} else {
return;
}
}
} else {
throw new Error(`${getClassPropertyName(resolvedClassType, resolvedPropertyName)} has no class defined. Use Circular decorator if that class really exists.`);
}
}
}
if (inClassField) {
isArray = false;
isMap = false;
if (resolvedTypeCandidate) {
return {
resolvedClassType: resolvedClassType,
resolvedPropertyName: resolvedPropertyName,
type: resolvedTypeCandidate,
typeValue: resolvedClassTypeCandidate,
array: isArray,
map: isMap,
};
}
}
const {type, typeValue} = getReflectionType(resolvedClassType, resolvedPropertyName);
if (type) {
return {
resolvedClassType: resolvedClassType,
resolvedPropertyName: resolvedPropertyName,
type: type,
typeValue: typeValue,
array: isArray,
map: isMap,
}
}
}
/**
* @hidden
*/
export function getReflectionType<T>(classType: ClassType<T>, propertyName: string): { type: Types | undefined, typeValue: any | undefined } {
let valueMap = cache.get(classType.prototype);
if (!valueMap) {
valueMap = new Map();
cache.set(classType.prototype, valueMap);
}
let value = valueMap.get('getReflectionType::' + propertyName);
if (undefined === value) {
const schema = getEntitySchema(classType).getPropertyOrUndefined(propertyName);
try {
if (schema) {
value = {
type: schema.type,
typeValue: schema.getResolvedClassTypeForValidType()
};
} else {
value = {
type: undefined,
typeValue: undefined
}
}
} catch (error) {
throw new Error(`${getClassPropertyName(classType, propertyName)}: ${error}`);
}
valueMap.set('getReflectionType::' + propertyName, value);
}
return value;
}
/**
* @hidden
*/
export function getParentReferenceClass<T>(classType: ClassType<T>, propertyName: string): any {
let valueMap = cache.get(classType.prototype);
if (!valueMap) {
valueMap = new Map();
cache.set(classType.prototype, valueMap);
}
let value = valueMap.get('ParentReferenceClass::' + propertyName);
if (undefined === value) {
if (getEntitySchema(classType).getProperty(propertyName).isParentReference) {
const {typeValue} = getReflectionType(classType, propertyName);
if (!typeValue) {
throw new Error(`${getClassPropertyName(classType, propertyName)} has @ParentReference but no @Class defined.`);
}
value = typeValue;
}
valueMap.set('ParentReferenceClass::' + propertyName, value || '');
}
return value;
}
/**
* @hidden
*/
export function propertyClassToPlain<T>(classType: ClassType<T>, propertyName: string, propertyValue: any) {
if (undefined === propertyValue) {
return undefined;
}
if (null === propertyValue) {
return null;
}
const reflection = getResolvedReflection(classType, propertyName);
if (!reflection) return propertyValue;
const {resolvedClassType, resolvedPropertyName, type, typeValue, array, map} = reflection;
function convert(value: any) {
if ('date' === type && value instanceof Date) {
return value.toJSON();
}
if ('string' === type) {
return String(value);
}
if ('enum' === type) {
//the class instance itself can only have the actual value which can be used in plain as well
return value;
}
if ('binary' === type && value.toString) {
return value.toString('base64');
}
if ('any' === type) {
return clone(value, false);
}
if (type === 'class') {
if (!(value instanceof typeValue)) {
throw new Error(
`Could not convert ${getClassPropertyName(classType, propertyName)} since target is not a `+
`class instance of ${getClassName(typeValue)}. Got ${getClassName(value)}`);
}
return classToPlain(typeValue, value);
}
return value;
}
if (array) {
if (isArray(propertyValue)) {
return propertyValue.map(v => convert(v));
}
return [];
}
if (map) {
const result: { [name: string]: any } = {};
if (isObject(propertyValue)) {
for (const i in propertyValue) {
if (!propertyValue.hasOwnProperty(i)) continue;
result[i] = convert((<any>propertyValue)[i]);
}
}
return result;
}
return convert(propertyValue);
}
/**
* @hidden
*/
export function propertyPlainToClass<T>(
classType: ClassType<T>,
propertyName: string,
propertyValue: any,
parents: any[],
incomingLevel: number,
state: ToClassState
) {
if (isUndefined(propertyValue)) {
return undefined;
}
if (null === propertyValue) {
return null;
}
const reflection = getResolvedReflection(classType, propertyName);
if (!reflection) return propertyValue;
const {resolvedClassType, resolvedPropertyName, type, typeValue, array, map} = reflection;
function convert(value: any) {
if ('date' === type && ('string' === typeof value || 'number' === typeof value)) {
return new Date(value);
}
if ('string' === type && 'string' !== typeof value) {
return String(value);
}
if ('number' === type && 'number' !== typeof value) {
return +value;
}
if ('binary' === type && 'string' === typeof value) {
return Buffer.from(value, 'base64');
}
if ('boolean' === type && 'boolean' !== typeof value) {
if ('true' === value || '1' === value || 1 === value) return true;
if ('false' === value || '0' === value || 0 === value) return false;
return true === value;
}
if ('any' === type) {
return clone(value, false);
}
if ('enum' === type) {
const allowLabelsAsValue = isEnumAllowLabelsAsValue(resolvedClassType, resolvedPropertyName);
if (undefined !== value && !isValidEnumValue(typeValue, value, allowLabelsAsValue)) {
const valids = getEnumValues(typeValue);
if (allowLabelsAsValue) {
for (const label of getEnumLabels(typeValue)) {
valids.push(label);
}
}
throw new Error(`Invalid ENUM given in property ${resolvedPropertyName}: ${value}, valid: ${valids.join(',')}`);
}
return getValidEnumValue(typeValue, value, allowLabelsAsValue);
}
if (type === 'class') {
if (value instanceof typeValue) {
//already the target type, this is an error
throw new Error(`${getClassPropertyName(resolvedClassType, resolvedPropertyName)} is already in target format. Are you calling plainToClass() with an class instance?`);
}
return toClass(typeValue, value, propertyPlainToClass, parents, incomingLevel, state);
}
return value;
}
if (array) {
if (isArray(propertyValue)) {
return propertyValue.map(v => convert(v));
}
return [];
}
if (map) {
const result: { [name: string]: any } = {};
if (isObject(propertyValue)) {
for (const i in propertyValue) {
if (!propertyValue.hasOwnProperty(i)) continue;
result[i] = convert((<any>propertyValue)[i]);
}
}
return result;
}
return convert(propertyValue);
}
/**
* Clones a class instance deeply.
*/
export function cloneClass<T>(target: T, parents?: any[]): T {
return plainToClass(target.constructor as ClassType<T>, classToPlain(target.constructor as ClassType<T>, target), parents);
}
/**
* Converts a class instance into a plain object, which an be used with JSON.stringify() to convert it into a JSON string.
*/
export function classToPlain<T>(classType: ClassType<T>, target: T): any {
const result: any = {};
if (!(target instanceof classType)) {
throw new Error(`Could not classToPlain since target is not a class instance of ${getClassName(classType)}`);
}
const decoratorName = getDecorator(classType);
if (decoratorName) {
return propertyClassToPlain(classType, decoratorName, (target as any)[decoratorName]);
}
const propertyNames = getRegisteredProperties(classType);
for (const propertyName of propertyNames) {
if (getParentReferenceClass(classType, propertyName)) {
//we do not export parent references, as this would lead to an circular reference
continue;
}
if (isExcluded(classType, propertyName, 'plain')) {
continue
}
result[propertyName] = propertyClassToPlain(classType, propertyName, (target as any)[propertyName]);
}
return result;
}
/**
* @hidden
*/
export class ToClassState {
onFullLoadCallbacks: (() => void)[] = [];
}
const propertyNamesCache = new Map<ClassType<any>, string[]>();
const parentReferencesCache = new Map<ClassType<any>, {[propertyName: string]: any}>();
/**
* @hidden
*/
function findParent<T>(parents: any[], parentType: ClassType<T>): T | null {
for (let i = parents.length - 1; i >= 0; i--) {
if (parents[i] instanceof parentType) {
return parents[i];
}
}
return null;
}
/**
* @hidden
*/
export function toClass<T>(
classType: ClassType<T>,
cloned: object,
converter: (classType: ClassType<T>, propertyName: string, propertyValue: any, parents: any[], incomingLevel: number, state: ToClassState) => any,
parents: any[],
incomingLevel,
state: ToClassState
): T {
const assignedViaConstructor: { [propertyName: string]: boolean } = {};
let propertyNames = propertyNamesCache.get(classType);
if (!propertyNames) {
propertyNames = getRegisteredProperties(classType);
propertyNamesCache.set(classType, propertyNames);
}
let parentReferences = parentReferencesCache.get(classType);
if (!parentReferences) {
parentReferences = {};
for (const propertyName of propertyNames) {
parentReferences[propertyName] = getParentReferenceClass(classType, propertyName);
}
parentReferencesCache.set(classType, parentReferences);
}
const parameterNames = getCachedParameterNames(classType);
const decoratorName = getDecorator(classType);
const backupedClone = cloned;
if (!isObject(cloned)) {
cloned = {};
}
const args: any[] = [];
for (const propertyName of parameterNames) {
if (decoratorName && propertyName === decoratorName) {
cloned[propertyName] = converter(classType, decoratorName, backupedClone, parents, incomingLevel, state);
} else if (parentReferences[propertyName]) {
const parent = findParent(parents, parentReferences[propertyName]);
if (parent) {
cloned[propertyName] = parent;
} else if (!isOptional(classType, propertyName)) {
throw new Error(`${getClassPropertyName(classType, propertyName)} is in constructor ` +
`has @ParentReference() and NOT @Optional(), but no parent of type ${getClassName(parentReferences[propertyName])} found. ` +
`In case of circular reference, remove '${propertyName}' from constructor, or make sure you provided all parents.`
);
}
} else {
cloned[propertyName] = converter(classType, propertyName, cloned[propertyName], parents, incomingLevel + 1, state);
}
assignedViaConstructor[propertyName] = true;
args.push(cloned[propertyName]);
}
const item = new classType(...args);
const parentsWithItem = parents.slice(0);
parentsWithItem.push(item);
for (const propertyName of propertyNames) {
if (assignedViaConstructor[propertyName]) {
//already given via constructor
continue;
}
if (parentReferences[propertyName]) {
const parent = findParent(parents, parentReferences[propertyName]);
if (parent) {
item[propertyName] = parent;
} else if (!isOptional(classType, propertyName)) {
throw new Error(`${getClassPropertyName(classType, propertyName)} is defined as @ParentReference() and `+
`NOT @Optional(), but no parent found. Add @Optional() or provide ${propertyName} in parents to fix that.`);
}
} else if (undefined !== cloned[propertyName]) {
item[propertyName] = converter(classType, propertyName, cloned[propertyName], parentsWithItem, incomingLevel + 1, state);
}
}
for (const onLoad of getEntitySchema(classType).onLoad) {
if (onLoad.options.fullLoad) {
state.onFullLoadCallbacks.push(() => {
item[onLoad.methodName]();
});
} else {
item[onLoad.methodName]();
}
}
return item;
}
/**
* Takes a regular object with partial fields defined of classType and converts only them into the class variant.
*
* Returns a new regular object again.
*/
export function partialPlainToClass<T, K extends keyof T>(classType: ClassType<T>, target: {[path: string]: any}, parents?: any[]): Partial<{[F in K]: any}> {
const result: Partial<{[F in K]: any}> = {};
const state = new ToClassState();
for (const i in target) {
if (!target.hasOwnProperty(i)) continue;
result[i] = propertyPlainToClass(classType, i, target[i], parents || [], 1, state);
}
return result;
}
/**
* Takes a object with partial class fields defined of classType and converts only them into the plain variant.
*
* Returns a new regular object again.
*/
export function partialClassToPlain<T, K extends keyof T>(classType: ClassType<T>, target: {[path: string]: any}): Partial<{[F in K]: any}> {
const result: Partial<{[F in K]: any}> = {};
for (const i in target) {
if (!target.hasOwnProperty(i)) continue;
result[i] = propertyClassToPlain(classType, i, target[i]);
}
return result;
}
/**
* Take a regular object with all fields default (missing default to class property default or undefined)
* and returns an instance of classType.
*/
export function plainToClass<T>(classType: ClassType<T>, target: object, parents?: any[]): T {
const state = new ToClassState();
const item = toClass(classType, target, propertyPlainToClass, parents || [], 1, state);
for (const callback of state.onFullLoadCallbacks) {
callback();
}
return item;
}
/**
* @hidden
*/
export function deleteExcludedPropertiesFor<T>(classType: ClassType<T>, item: any, target: 'mongo' | 'plain') {
for (const propertyName in item) {
if (!item.hasOwnProperty(propertyName)) continue;
if (isExcluded(classType, propertyName, target)) {
delete item[propertyName];
}
}
}
/**
* @hidden
*/
export function getIdField<T>(classType: ClassType<T>): string | undefined {
return getEntitySchema(classType).idField;
}
/**
* @hidden
*/
export function getIdFieldValue<T>(classType: ClassType<T>, target: any): any {
const id = getIdField(classType);
return id ? target[id] : undefined;
}
/**
* @hidden
*/
export function getDecorator<T>(classType: ClassType<T>): string | undefined {
return getEntitySchema(classType).decorator;
}
/**
* @hidden
*/
export function getRegisteredProperties<T>(classType: ClassType<T>): string[] {
return getEntitySchema(classType).propertyNames;
}
/**
* @hidden
*/
export function isArrayType<T>(classType: ClassType<T>, property: string): boolean {
return getEntitySchema(classType).getProperty(property).isArray;
}
/**
* @hidden
*/
export function isMapType<T>(classType: ClassType<T>, property: string): boolean {
return getEntitySchema(classType).getProperty(property).isMap;
}
/**
* @hidden
*/
export function isEnumAllowLabelsAsValue<T>(classType: ClassType<T>, property: string): boolean {
return getEntitySchema(classType).getProperty(property).allowLabelsAsValue;
}
/**
* @hidden
*/
export function isExcluded<T>(classType: ClassType<T>, property: string, wantedTarget: 'mongo' | 'plain'): boolean {
const mode = getEntitySchema(classType).getProperty(property).exclude;
if ('all' === mode) {
return true;
}
return mode === wantedTarget;
}
export function getEntityName<T>(classType: ClassType<T>): string {
const name = getEntitySchema(classType).name;
if (!name) {
throw new Error('No @Entity() defined for class ' + classType);
}
return name;
}
/**
* @hidden
*/
export function getDatabaseName<T>(classType: ClassType<T>): string | undefined {
return getEntitySchema(classType).databaseName;
}
/**
* @hidden
*/
export function getCollectionName<T>(classType: ClassType<T>): string | undefined {
return getEntitySchema(classType).collectionName;
}
/**
* @hidden
*/
export function applyDefaultValues<T>(classType: ClassType<T>, value: { [name: string]: any }): object {
if (!isObject(value)) return {};
const valueWithDefaults = value;
const instance = plainToClass(classType, value);
for (const i of getRegisteredProperties(classType)) {
if (undefined === value[i]) {
valueWithDefaults[i] = (instance as any)[i];
}
}
return valueWithDefaults;
}