/
attribute.decorator.ts
58 lines (50 loc) · 1.88 KB
/
attribute.decorator.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
import 'reflect-metadata';
import * as moment from 'moment';
export function Attribute(config: any = {}) {
return function (target: any, propertyName: string) {
let converter = function(dataType: any, value: any, forSerialisation = false): any {
if (!forSerialisation) {
if (dataType === Date) {
return moment.utc(value).toDate();
}
} else {
if (dataType === Date) {
return moment(value).format(moment.defaultFormatUtc);
}
}
return value;
};
let saveAnnotations = function (hasDirtyAttributes: boolean, oldValue: any, newValue: any, isNew: boolean) {
let annotations = Reflect.getMetadata('Attribute', target) || {};
let targetType = Reflect.getMetadata('design:type', target, propertyName);
hasDirtyAttributes = typeof oldValue === 'undefined' && !isNew ? false : hasDirtyAttributes;
annotations[propertyName] = {
hasDirtyAttributes: hasDirtyAttributes,
oldValue: oldValue,
newValue: newValue,
serialisationValue: converter(targetType, newValue, true)
};
Reflect.defineMetadata('Attribute', annotations, target);
};
let getter = function () {
return this['_' + propertyName];
};
let setter = function (newVal: any) {
let targetType = Reflect.getMetadata('design:type', target, propertyName);
let convertedValue = converter(targetType, newVal);
if (convertedValue !== this['_' + propertyName]) {
saveAnnotations(true, this['_' + propertyName], newVal, !this.id);
this['_' + propertyName] = convertedValue;
}
};
if (delete target[propertyName]) {
saveAnnotations(false, undefined, target[propertyName], target.id);
Object.defineProperty(target, propertyName, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
};
}