-
Notifications
You must be signed in to change notification settings - Fork 116
/
decorators.ts
1416 lines (1222 loc) · 43.2 KB
/
decorators.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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {Types} from "./mapper";
import {
BooleanValidator,
DateValidator,
NumberValidator,
ObjectIdValidator,
PropertyValidatorError,
StringValidator,
UUIDValidator
} from "./validation";
import {ClassType, eachKey, eachPair, getClassName, isClass, isNumber, isObject, isPlainObject} from '@marcj/estdlib';
import {Buffer} from "buffer";
import * as getParameterNames from "get-parameter-names";
/**
* Registry of all registered entity that used the @Entity('name') decorator.
*/
export const RegisteredEntities: { [name: string]: ClassType<any> } = {};
export interface PropertyValidator {
validate<T>(value: any, target: ClassType<T>, propertyName: string, propertySchema: PropertySchema): PropertyValidatorError | void;
}
export function isPropertyValidator(object: any): object is ClassType<PropertyValidator> {
return isClass(object);
}
type IndexOptions = Partial<{
unique: boolean,
spatial: boolean,
sparse: boolean,
synchronize: boolean,
fulltext: boolean,
where: string,
}>;
/**
* Represents a class property or method argument definition.
*/
export class PropertySchema {
name: string;
type: Types = 'any';
isArray: boolean = false;
isMap: boolean = false;
typeSet: boolean = false;
/**
* Whether this property is decorated.
*/
isDecorated: boolean = false;
isParentReference: boolean = false;
isOptional: boolean = false;
isId: boolean = false;
/**
* When this property belongs to method as argument then this contains the name of the method.
*/
methodName?: string;
readonly validators: ClassType<PropertyValidator>[] = [];
/**
* For enums.
*/
allowLabelsAsValue: boolean = false;
exclude?: 'all' | 'mongo' | 'plain';
classType?: ClassType<any>;
classTypeForwardRef?: ForwardedRef<any>;
classTypeResolved?: ClassType<any>;
constructor(name: string) {
this.name = name;
}
static getTypeFromJSType(type: any) {
if (type === String) {
return 'string';
}
if (type === Number) {
return 'number';
}
if (type === Date) {
return 'date';
}
if (type === Buffer) {
return 'binary';
}
if (type === Boolean) {
return 'boolean';
}
return 'any';
}
setFromJSType(type: any) {
this.type = PropertySchema.getTypeFromJSType(type);
const isCustomObject = type !== String
&& type !== String
&& type !== Number
&& type !== Date
&& type !== Buffer
&& type !== Boolean
&& type !== Any
&& type !== Object;
if (isCustomObject) {
this.type = 'class';
this.classType = type as ClassType<any>;
if (type instanceof ForwardedRef) {
this.classTypeForwardRef = type;
delete this.classType;
}
}
}
clone(): PropertySchema {
const s = new PropertySchema(this.name);
for (const i of eachKey(this)) {
s[i] = this[i];
}
return s;
}
getForeignClassDecorator(): PropertySchema | undefined {
if (this.type === 'class') {
const targetClass = this.getResolvedClassType();
if (getClassSchema(targetClass).decorator) {
return getClassSchema(targetClass).getDecoratedPropertySchema();
}
}
}
getValidators(): ClassType<PropertyValidator>[] {
if (this.type === 'string') {
return [StringValidator, ...this.validators];
}
if (this.type === 'date') {
return [DateValidator, ...this.validators];
}
if (this.type === 'number') {
return [NumberValidator, ...this.validators];
}
if (this.type === 'uuid') {
return [UUIDValidator, ...this.validators];
}
if (this.type === 'objectId') {
return [ObjectIdValidator, ...this.validators];
}
if (this.type === 'boolean') {
return [BooleanValidator, ...this.validators];
}
return this.validators;
}
getResolvedClassTypeForValidType(): ClassType<any> | undefined {
if (this.type === 'class' || this.type === 'enum') {
return this.getResolvedClassType();
}
}
isResolvedClassTypeIsDecorated(): boolean {
if (this.type === 'class') {
const foreignSchema = getClassSchema(this.getResolvedClassType());
return Boolean(foreignSchema.decorator);
}
return false;
}
getResolvedClassType(): ClassType<any> {
if (this.classTypeResolved) {
return this.classTypeResolved;
}
if (this.classTypeForwardRef) {
this.classTypeResolved = this.classTypeForwardRef.forward();
if (this.classTypeResolved) {
return this.classTypeResolved;
}
throw new Error(`ForwardRef returns no value. ${this.classTypeForwardRef.forward}`);
}
if (!this.classType) {
throw new Error(`No classType given for ${this.name}. Use @f.forward(() => MyClass) for circular dependencies.`);
}
return this.classType;
}
}
export interface EntityIndex {
name: string,
fields: string[],
options: IndexOptions
}
export class ClassSchema {
proto: Object;
name?: string;
collectionName?: string;
databaseName?: string;
decorator?: string;
/**
* Each method can have its own PropertySchema definition for each argument, where map key = method name.
*/
methodProperties = new Map<string, PropertySchema[]>();
normalizedMethodProperties: { [name: string]: true } = {};
classProperties: { [name: string]: PropertySchema } = {};
idField?: string;
propertyNames: string[] = [];
methodsParamNames = new Map<string, string[]>();
methodsParamNamesAutoResolved = new Map<string, string[]>();
indices: EntityIndex[] = [];
onLoad: { methodName: string, options: { fullLoad?: boolean } }[] = [];
constructor(proto: Object) {
this.proto = proto;
}
public clone(proto: Object): ClassSchema {
const s = new ClassSchema(proto);
s.name = this.name;
s.collectionName = this.collectionName;
s.databaseName = this.databaseName;
s.decorator = this.decorator;
s.classProperties = {};
for (const [i, v] of eachPair(this.classProperties)) {
s.classProperties[i] = v.clone();
}
s.methodProperties = new Map();
for (const [i, properties] of this.methodProperties.entries()) {
const obj: PropertySchema[] = [];
for (const v of properties) {
obj.push(v.clone());
}
s.methodProperties.set(i, obj);
}
s.idField = this.idField;
s.propertyNames = this.propertyNames.slice(0);
s.methodsParamNames = new Map<string, string[]>();
s.methodsParamNamesAutoResolved = new Map<string, string[]>();
for (const [m, p] of this.methodsParamNames.entries()) s.methodsParamNames.set(m, p.slice(0));
for (const [m, p] of this.methodsParamNamesAutoResolved.entries()) s.methodsParamNamesAutoResolved.set(m, p.slice(0));
s.indices = [];
for (const v of this.indices) {
s.indices.push({...v});
}
s.onLoad = [];
for (const v of this.onLoad) {
s.onLoad.push({...v});
}
return s;
}
/**
* Returns all annotated arguments as PropertSchema for given method name.
*
* notice: The user is allowed to annotated partial arguments, which means you end up having
* in this array only a subset of annotated method arguments. Check always for undefined when accessing an
* array item.
*/
public getMethodProperties(name: string): PropertySchema[] {
const properties = this.getOrCreateMethodProperties(name);
if (!this.normalizedMethodProperties[name]) {
const returnTypes = Reflect.getMetadata('design:paramtypes', this.proto, name);
if (!returnTypes) {
throw new Error(`Method ${name} has no decorated used, so reflection does not work.`);
}
for (const [i, t] of eachPair(returnTypes)) {
if (!properties[i]) {
properties[i] = new PropertySchema(String(i));
if (properties[i].type === 'any' && returnTypes[i] !== Object) {
properties[i].setFromJSType(t)
}
}
}
this.normalizedMethodProperties[name] = true;
}
return properties;
}
/**
* @internal
*/
public getOrCreateMethodProperties(name: string): PropertySchema[] {
if (!this.methodProperties.has(name)) {
this.methodProperties.set(name, []);
}
return this.methodProperties.get(name)!;
}
public getClassProperties(): { [name: string]: PropertySchema } {
return this.classProperties;
}
/**
* @internal
*/
public getMethodsParamNames(methodName: string): string[] {
if (!this.methodsParamNames.has(methodName)) this.methodsParamNames.set(methodName, []);
return this.methodsParamNames.get(methodName)!;
}
/**
* @internal
*/
public getMethodsParamNamesAutoResolved(methodName: string): string[] {
if (!this.methodsParamNamesAutoResolved.has(methodName)) this.methodsParamNamesAutoResolved.set(methodName, []);
return this.methodsParamNamesAutoResolved.get(methodName)!;
}
public getDecoratedPropertySchema(): PropertySchema {
if (!this.decorator) {
throw new Error(`No decorated property found`);
}
return this.getProperty(this.decorator);
}
public getIndex(name: string): EntityIndex | undefined {
for (const index of this.indices) {
if (index.name === name) {
return index;
}
}
}
public getPropertyOrUndefined(name: string): PropertySchema | undefined {
if (this.classProperties[name]) {
return this.classProperties[name];
}
}
public hasProperty(name: string): boolean {
return Boolean(this.classProperties[name]);
}
public getProperty(name: string): PropertySchema {
if (!this.classProperties[name]) {
throw new Error(`Property ${name} not found`);
}
return this.classProperties[name];
}
}
/**
* @hidden
*/
export const ClassSchemas = new Map<object, ClassSchema>();
/**
* @hidden
*/
export function getOrCreateEntitySchema<T>(target: Object | ClassType<T>): ClassSchema {
const proto = target['prototype'] ? target['prototype'] : target;
if (!ClassSchemas.has(proto)) {
//check if parent has a EntitySchema, if so clone and use it as base.
let currentProto = Object.getPrototypeOf(proto);
let found = false;
while (currentProto && currentProto !== Object.prototype) {
if (ClassSchemas.has(currentProto)) {
found = true;
ClassSchemas.set(proto, ClassSchemas.get(currentProto)!.clone(proto));
break;
}
currentProto = Object.getPrototypeOf(currentProto);
}
if (!found) {
const reflection = new ClassSchema(proto);
ClassSchemas.set(proto, reflection);
}
}
return ClassSchemas.get(proto)!;
}
/**
* Returns meta information / schema about given entity class.
*/
export function getClassSchema<T>(classType: ClassType<T>): ClassSchema {
if (!ClassSchemas.has(classType.prototype)) {
//check if parent has a EntitySchema, if so clone and use it as base.
let currentProto = Object.getPrototypeOf(classType.prototype);
let found = false;
while (currentProto && currentProto !== Object.prototype) {
if (ClassSchemas.has(currentProto)) {
found = true;
ClassSchemas.set(classType.prototype, ClassSchemas.get(currentProto)!.clone(classType.prototype));
break;
}
currentProto = Object.getPrototypeOf(currentProto);
}
if (!found) {
const reflection = new ClassSchema(classType.prototype);
ClassSchemas.set(classType.prototype, reflection);
}
}
return ClassSchemas.get(classType.prototype)!;
}
/**
* Returns the ClassType for a given instance.
*/
export function getClassTypeFromInstance<T>(target: T): ClassType<T> {
if (!target
|| !target['constructor']
|| Object.getPrototypeOf(target) !== target['constructor'].prototype
|| isPlainObject(target)
|| !isObject(target)
) {
throw new Error('Target does not seem to be a class instance.');
}
return target['constructor'] as ClassType<T>;
}
/**
* Returns true if given class has an @Entity() or @f defined, and thus became
* a Marshal entity.
*/
export function isRegisteredEntity<T>(classType: ClassType<T>): boolean {
return ClassSchemas.has(classType.prototype);
}
/**
* Used to define a entity name for an entity.
*
* The name is used for an internal registry, so ot should be a unique one.
*
* Marshal's database abstraction uses this name to generate the collection name / table name.
*
* @category Decorator
*/
export function Entity<T>(name: string, collectionName?: string) {
return (target: ClassType<T>) => {
if (RegisteredEntities[name]) {
throw new Error(`Marshal entity with name '${name}' already registered.
This could be caused by the fact that you used a name twice or that you loaded the entity
via different imports.`)
}
RegisteredEntities[name] = target;
getOrCreateEntitySchema(target).name = name;
getOrCreateEntitySchema(target).collectionName = collectionName;
};
}
/**
* Used to define a database name for an entity. Per default marshal's database abstraction
* uses the default database, but you can change that using this decorator.
*
* @category Decorator
*/
export function DatabaseName<T>(name: string) {
return (target: ClassType<T>) => {
getOrCreateEntitySchema(target).databaseName = name;
};
}
export interface FieldDecoratorResult {
(target: Object, property?: string, parameterIndexOrDescriptor?: any): void;
/**
* Sets the name of this property. Important for cases where the actual name is lost during compilation.
*/
asName(name: string): FieldDecoratorResult;
/**
* Marks this field as optional. The validation requires field values per default, this makes it optional.
*/
optional(): FieldDecoratorResult;
/**
* Used to define a field as excluded when serialized from class to different targets (currently to Mongo or JSON).
* PlainToClass or mongoToClass is not effected by this.
*/
exclude(t?: 'all' | 'mongo' | 'plain'): FieldDecoratorResult;
/**
* Marks this field as an ID aka primary.
* This is important if you interact with the database abstraction.
*
* Only one field in a class can be the ID.
*/
primary(): FieldDecoratorResult;
/**
* @see primary
* @deprecated
*/
asId(): FieldDecoratorResult;
/**
* Used to define an index on a field.
*/
index(options?: IndexOptions, name?: string): FieldDecoratorResult;
/**
* Used to define a field as MongoDB ObjectId. This decorator is necessary if you want to use Mongo's _id.
*
* ```typescript
* class Page {
* @f.mongoId()
* referenceToSomething?: string;
*
* constructor(
* @f.id().mongoId()
* public readonly _id: string
* ) {
*
* }
* }
* ```
*/
mongoId(): FieldDecoratorResult;
/**
* Used to define a field as UUID (v4).
*/
uuid(): FieldDecoratorResult;
/**
* Used to define a field as decorated.
* This is necessary if you want to wrap a field value in the class instance using
* a own class, like for example for Array manipulations, but keep the JSON and Database value
* as primitive as possible.
*
* Only one field per class can be the decorated one.
*
* @category Decorator
*
* Example
* ```typescript
* export class PageCollection {
* @f.forward(() => PageClass).decorated()
* private readonly pages: PageClass[] = [];
*
* constructor(pages: PageClass[] = []) {
* this.pages = pages;
* }
*
* public count(): number {
* return this.pages.length;
* }
*
* public add(name: string): number {
* return this.pages.push(new PageClass(name));
* }
* }
*
* export class PageClass {
* @f.uuid()
* id: string = uuid();
*
* @f
* name: string;
*
* @f.forward(() => PageCollection)
* children: PageCollection = new PageCollection;
*
* constructor(name: string) {
* this.name = name;
* }
* }
* ```
*
* If you use classToPlain(PageClass, ...) or classToMongo(PageClass, ...) the field value of `children` will be the type of
* `PageCollection.pages` (always the field where @Decorated() is applied to), here a array of PagesClass `PageClass[]`.
*/
decorated(): FieldDecoratorResult;
/**
* Marks a field as array. You should prefer `@f.array(T)` syntax.
*
* ```typescript
* class User {
* @f.type(String).asArray()
* tags: strings[] = [];
* }
* ```
*/
asArray(): FieldDecoratorResult;
/**
* Marks a field as map. You should prefer `@f.map(T)` syntax.
*
* ```typescript
* class User {
* @f.type(String).asMap()
* tags: {[name: string]: string} = [];
* }
* ```
*/
asMap(): FieldDecoratorResult;
/**
* Uses an additional decorator.
*/
use(decorator: (target: Object, propertyOrMethodName?: string, parameterIndexOrDescriptor?: any) => void): FieldDecoratorResult;
/**
* Adds a custom validator class or validator callback.
*
* @example
* ```typescript
* import {PropertyValidator, PropertyValidatorError} from '@marcj/marshal';
*
* class MyCustomValidator implements PropertyValidator {
* async validate<T>(value: any, target: ClassType<T>, propertyName: string): PropertyValidatorError | void {
* if (value.length > 10) {
* return new PropertyValidatorError('too_long', 'Too long :()');
* }
* };
* }
*
* class Entity {
* @f.validator(MyCustomValidator)
* name: string;
*
* @f.validator(MyCustomValidator)
* name: string;
*
* @f.validator((value: any, target: ClassType<any>, propertyName: string) => {
* if (value.length > 255) {
* return new PropertyValidatorError('too_long', 'Too long :()');
* }
* })
* title: string;
* }
*
* ```
*/
validator(validator: ClassType<PropertyValidator> | ((value: any, target: ClassType<any>, propertyName: string) => PropertyValidatorError | void)):
FieldDecoratorResult;
}
function createFieldDecoratorResult(
cb: (target: Object, property: PropertySchema, returnType: any, modifiedOptions: FieldOptions) => void,
givenPropertyName: string = '',
modifier: ((target: Object, propertyOrMethodName?: string, parameterIndexOrDescriptor?: any) => void)[] = [],
modifiedOptions: FieldOptions = {},
root = false,
): FieldDecoratorResult {
function resetIfNecessary() {
//on root we never use the overwritten name, so we set it back
//for child FieldDecoratorResults created via asName() etc we keep that stuff (since there is root=false)
if (root) {
givenPropertyName = '';
modifier = [];
modifiedOptions = {};
}
}
const fn = (target: Object, propertyOrMethodName?: string, parameterIndexOrDescriptor?: any) => {
resetIfNecessary();
let returnType;
let methodName = 'constructor';
const schema = getOrCreateEntitySchema(target);
if (isNumber(parameterIndexOrDescriptor)) {
//decorator is used on a method argument
methodName = propertyOrMethodName || 'constructor';
const methodsParamNames = schema.getMethodsParamNames(methodName);
const methodsParamNamesAutoResolved = schema.getMethodsParamNamesAutoResolved(methodName);
if (!givenPropertyName && methodsParamNames[parameterIndexOrDescriptor]) {
givenPropertyName = methodsParamNames[parameterIndexOrDescriptor];
}
if (givenPropertyName && (
(methodsParamNames[parameterIndexOrDescriptor] && methodsParamNames[parameterIndexOrDescriptor] !== givenPropertyName)
|| (methodsParamNamesAutoResolved[parameterIndexOrDescriptor] && methodsParamNamesAutoResolved[parameterIndexOrDescriptor] !== givenPropertyName)
)
) {
//we got a new decorator with a different name on a constructor param
//since we cant not resolve logically which name to use, we forbid that case.
throw new Error(`Defining multiple Marshal decorators with different names at arguments of ${getClassName(target)}::${methodName} #${parameterIndexOrDescriptor} is forbidden.` +
` @f.asName('name') is required. Got ${methodsParamNames[parameterIndexOrDescriptor] || methodsParamNamesAutoResolved[parameterIndexOrDescriptor]} !== ${givenPropertyName}`)
}
if (givenPropertyName) {
//we only store the name, when we explicitly defined one
methodsParamNames[parameterIndexOrDescriptor] = givenPropertyName;
} else if (methodName === 'constructor') {
//only for constructor methods
const constructorParamNames = getParameterNames((target as ClassType<any>).prototype.constructor);
// const constructorParamNames = getCachedParameterNames((target as ClassType<any>).prototype.constructor);
givenPropertyName = constructorParamNames[parameterIndexOrDescriptor];
if (givenPropertyName) {
methodsParamNamesAutoResolved[parameterIndexOrDescriptor] = givenPropertyName;
}
}
if (methodName === 'constructor') {
//constructor
const returnTypes = Reflect.getMetadata('design:paramtypes', target);
if (returnTypes) returnType = returnTypes[parameterIndexOrDescriptor];
} else {
//method
const returnTypes = Reflect.getMetadata('design:paramtypes', target, methodName);
if (returnTypes) returnType = returnTypes[parameterIndexOrDescriptor];
}
} else {
//it's a class property, so propertyOrMethodName contains the actual property name
if (propertyOrMethodName) {
returnType = Reflect.getMetadata('design:type', target, propertyOrMethodName);
}
if (!givenPropertyName && propertyOrMethodName) {
givenPropertyName = propertyOrMethodName;
}
}
const argumentsProperties = schema.getOrCreateMethodProperties(methodName);
let propertySchema: PropertySchema | undefined = undefined;
if (isNumber(parameterIndexOrDescriptor)) {
//decorator is used on a method argument. Might be on constructor or any other method.
if (methodName === 'constructor') {
if (!schema.classProperties[givenPropertyName]) {
schema.classProperties[givenPropertyName] = new PropertySchema(givenPropertyName);
schema.propertyNames.push(givenPropertyName);
}
propertySchema = schema.classProperties[givenPropertyName];
argumentsProperties[parameterIndexOrDescriptor] = propertySchema;
} else {
if (!argumentsProperties[parameterIndexOrDescriptor]) {
argumentsProperties[parameterIndexOrDescriptor] = new PropertySchema(String(parameterIndexOrDescriptor));
argumentsProperties[parameterIndexOrDescriptor].methodName = methodName;
}
propertySchema = argumentsProperties[parameterIndexOrDescriptor];
}
} else {
if (!givenPropertyName) {
throw new Error(`Could not resolve property name for class property on ${getClassName(target)}`);
}
if (!schema.classProperties[givenPropertyName]) {
schema.classProperties[givenPropertyName] = new PropertySchema(givenPropertyName);
schema.propertyNames.push(givenPropertyName);
}
propertySchema = schema.classProperties[givenPropertyName];
}
for (const mod of modifier) {
mod(target, propertyOrMethodName, parameterIndexOrDescriptor);
}
if (isNumber(parameterIndexOrDescriptor) && target['prototype']) {
target = target['prototype'];
}
cb(target, propertySchema!, returnType, {...modifiedOptions});
};
fn.asName = (name: string) => {
resetIfNecessary();
return createFieldDecoratorResult(cb, name, [...modifier, Optional()], modifiedOptions);
};
fn.optional = () => {
resetIfNecessary();
return createFieldDecoratorResult(cb, givenPropertyName, [...modifier, Optional()], modifiedOptions);
};
fn.exclude = (target: 'all' | 'mongo' | 'plain' = 'all') => {
resetIfNecessary();
return createFieldDecoratorResult(cb, givenPropertyName, [...modifier, Exclude(target)], modifiedOptions);
};
fn.primary = fn.asId = () => {
resetIfNecessary();
return createFieldDecoratorResult(cb, givenPropertyName, [...modifier, IDField()], modifiedOptions);
};
fn.index = (options?: IndexOptions, name?: string) => {
resetIfNecessary();
return createFieldDecoratorResult(cb, givenPropertyName, [...modifier, Index(options, name)], modifiedOptions);
};
fn.mongoId = () => {
resetIfNecessary();
return createFieldDecoratorResult(cb, givenPropertyName, [...modifier, MongoIdField()], modifiedOptions);
};
fn.uuid = () => {
resetIfNecessary();
return createFieldDecoratorResult(cb, givenPropertyName, [...modifier, UUIDField()], modifiedOptions);
};
fn.decorated = () => {
resetIfNecessary();
return createFieldDecoratorResult(cb, givenPropertyName, [...modifier, Decorated()], modifiedOptions);
};
fn.use = (decorator: (target: Object, propertyOrMethodName?: string, parameterIndexOrDescriptor?: any) => void) => {
resetIfNecessary();
return createFieldDecoratorResult(cb, givenPropertyName, [...modifier, decorator], modifiedOptions);
};
fn.asArray = () => {
resetIfNecessary();
if (modifiedOptions.map) throw new Error('Field is already defined as map.');
return createFieldDecoratorResult(cb, givenPropertyName, modifier, {...modifiedOptions, array: true});
};
fn.asMap = () => {
resetIfNecessary();
if (modifiedOptions.array) throw new Error('Field is already defined as array.');
return createFieldDecoratorResult(cb, givenPropertyName, modifier, {...modifiedOptions, map: true});
};
fn.validator = (validator: ClassType<PropertyValidator> | ((value: any, target: ClassType<any>, propertyName: string) => PropertyValidatorError | void)) => {
resetIfNecessary();
const validatorClass: ClassType<PropertyValidator> = isPropertyValidator(validator) ? validator : class implements PropertyValidator {
validate<T>(value: any, target: ClassType<T>, propertyName: string): PropertyValidatorError | void {
try {
return validator(value, target, propertyName);
} catch (error) {
return new PropertyValidatorError('error', error.message ? error.message : error);
}
}
};
return createFieldDecoratorResult(cb, givenPropertyName, [...modifier, FieldDecoratorWrapper((target, property) => {
property.validators.push(validatorClass);
})], modifiedOptions);
};
return fn;
}
/**
* Helper for decorators that are allowed to be placed in property declaration and constructor property declaration.
* We detect the name by reading the constructor' signature, which would be otherwise lost.
*/
export function FieldDecoratorWrapper(
cb: (target: Object, property: PropertySchema, returnType: any, modifiedOptions: FieldOptions) => void,
root = false
): FieldDecoratorResult {
return createFieldDecoratorResult(cb, '', [], {}, root);
}
/**
* @internal
*/
function Decorated() {
return FieldDecoratorWrapper((target, property) => {
getOrCreateEntitySchema(target).decorator = property.name;
property.isDecorated = true;
});
}
/**
* @internal
*/
function IDField() {
return FieldDecoratorWrapper((target, property) => {
getOrCreateEntitySchema(target).idField = property.name;
property.isId = true;
});
}
/**
* @internal
*/
function Optional() {
return FieldDecoratorWrapper((target, property) => {
property.isOptional = true;
});
}
/**
* Used to define a field as a reference to a parent.
*
* @category Decorator
*
* Example one direction.
* ```typescript
* class JobConfig {
* @f.forward(() => Job) //forward necessary since circular dependency
* @ParentReference()
* job: Job;
*
* }
*
* class Job {
* @f config: JobConfig;
* }
* ```
*
* Example circular parent-child setup.
* ```typescript
* export class PageClass {
* @f.uuid()
* id: string = uuid();
*
* @f
* name: string;
*
* @f.forwardArray(() => PageClass) //forward necessary since circular dependency
* children: Page[] = [];
*
* @f.forward(() => PageClass).optional() //forward necessary since circular dependency
* @ParentReference()
* parent?: PageClass;
*
* constructor(name: string) {
* this.name = name;
* }
* ```
*/
export function ParentReference() {
return FieldDecoratorWrapper((target, property) => {
property.isParentReference = true;
});
}
/**
* Used to define a method as callback which will be called when the object has been completely serialized.
* When fullLoad is true the callback is called when all references are loaded as well. This is particularly useful
* when you have @ParentReference() properties, which will be undefined in regular OnLoad callback.
*
* Example
* ```typescript
* class User {
* @OnLoad()
* onLoad() {
* console.log('self loaded!');
* }
*
* @OnLoad({fullLoad: true})
* onFullLoad() {
* console.log('fully loaded, including parent references');
* }
* }
*
* ```
*
* @category Decorator
*/
export function OnLoad<T>(options: { fullLoad?: boolean } = {}) {
return (target: T, property: string) => {
getOrCreateEntitySchema(target).onLoad.push({
methodName: property,
options: options,
});
};
}
/**
* @internal
*/
function Exclude(t: 'all' | 'mongo' | 'plain' = 'all') {
return FieldDecoratorWrapper((target, property) => {
property.exclude = t;
});