-
-
Notifications
You must be signed in to change notification settings - Fork 529
/
Property.ts
70 lines (62 loc) · 2.27 KB
/
Property.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
import { MetadataStorage, MetadataValidator } from '../metadata';
import { Utils } from '../utils';
import { Cascade, ReferenceType, LoadStrategy } from '../enums';
import { EntityName, EntityProperty, AnyEntity, Constructor } from '../typings';
import { Type } from '../types';
export function Property<T>(options: PropertyOptions<T> = {}) {
return function (target: AnyEntity, propertyName: string) {
const meta = MetadataStorage.getMetadataFromDecorator(target.constructor);
const desc = Object.getOwnPropertyDescriptor(target, propertyName) || {};
MetadataValidator.validateSingleDecorator(meta, propertyName, ReferenceType.SCALAR);
const name = options.name || propertyName;
if (propertyName !== name && !(desc.value instanceof Function)) {
Utils.renameKey(options, 'name', 'fieldName');
}
options.name = propertyName;
const prop = Object.assign({ reference: ReferenceType.SCALAR }, options) as EntityProperty;
prop.getter = !!desc.get;
prop.setter = !!desc.set;
if (desc.value instanceof Function) {
prop.getter = true;
prop.persist = false;
prop.type = 'method';
prop.getterName = propertyName;
prop.name = name;
}
meta.properties[prop.name] = prop;
return Utils.propertyDecoratorReturnValue();
};
}
export type PropertyOptions<T> = {
name?: string;
fieldName?: string;
fieldNames?: string[];
customType?: Type<any>;
columnType?: string;
type?: 'string' | 'number' | 'boolean' | 'bigint' | 'ObjectId' | string | unknown | bigint | Date | Constructor<Type<any>> | Type<any>;
length?: number;
onCreate?: (entity: T) => any;
onUpdate?: (entity: T) => any;
default?: string | string[] | number | number[] | boolean | null;
defaultRaw?: string;
formula?: string | ((alias: string) => string);
nullable?: boolean;
unsigned?: boolean;
persist?: boolean;
hidden?: boolean;
version?: boolean;
index?: boolean | string;
unique?: boolean | string;
lazy?: boolean;
primary?: boolean;
serializedPrimaryKey?: boolean;
serializer?: (value: any) => any;
serializedName?: string;
comment?: string;
};
export interface ReferenceOptions<T, O> extends PropertyOptions<O> {
entity?: string | (() => EntityName<T>);
cascade?: Cascade[];
eager?: boolean;
strategy?: LoadStrategy;
}