-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathXMLAttribute.ts
65 lines (53 loc) · 1.9 KB
/
XMLAttribute.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
import { XMLElement } from './XMLElement';
import { IXMLAttributeOptions } from '../interfaces/IXMLAttributeOptions';
import { IFullXMLAttributeOptions } from '../interfaces/IFullXMLAttributeOptions';
import { ICustomXMLAttributeOptions } from '../interfaces/ICustomXMLAttributeOptions';
import { createCustomGetter } from '../utils';
export class XMLAttribute {
private name: string;
static annotate(
target: any,
key: string,
options: IXMLAttributeOptions = {},
descriptor?: TypedPropertyDescriptor<any>
): void {
const element = XMLElement.getOrCreateIfNotExists(target);
const fullOptions = {
getter(entity: any): any {
if (descriptor && descriptor.get) {
return descriptor.get.call(entity);
}
return entity[key];
},
...options
};
fullOptions.name = options.name || key;
element.addAttribute(new XMLAttribute(fullOptions as IFullXMLAttributeOptions));
}
static createAttribute(options: ICustomXMLAttributeOptions): XMLAttribute {
const hasGetter = typeof options.getter === 'function';
const hasValue = options.value !== void 0;
if ((hasGetter && hasValue) || (!hasGetter && !hasValue)) {
throw new Error(`Either a getter or a value has to be defined for attribute "${options.name}".`);
}
const fullOptions = {
getter: createCustomGetter(options),
...options
};
return new XMLAttribute(fullOptions);
}
setSchema(target: any, entity: any): void {
const value = this.options.getter.call(null, entity);
if (value !== void 0) {
target[this.name] = value;
} else if (this.options.required) {
throw new Error(`Attribute ${this.name} is required, but empty.`);
}
}
private constructor(private options: IFullXMLAttributeOptions) {
this.name = options.name;
if (options.namespace) {
this.name = options.namespace + ':' + this.name;
}
}
}