-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
106 lines (97 loc) · 3.02 KB
/
index.js
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
/**
* Validate if the value is a string
* @param {*} value
*/
function isFieldSimple(value) {
return typeof value === 'string';
}
/**
* Validate if the value is a function
* @param {*} value
*/
function isFieldFunction(value) {
return typeof value === 'function';
};
/**
* Validate if the value is a object
* @param {*} value
*/
function isFieldObject(value) {
return typeof value === 'object' && value.constructor === Object;
};
/**
* Validate if the value is a array
* @param {*} value
*/
function isFieldArray(value) {
return typeof value === 'object' && value.constructor === Array;
};
/**
* New instance Transformer
* @param {*} obj properties
*/
function Transformer(obj) {
var keysObject = Object.keys(obj);
for (var i = 0; i < keysObject.length; i++) {
var property = obj[keysObject[i]];
if (isFieldObject(property)) {
if (!property.hasOwnProperty('field')) {
throw "The field {" + keysObject[i] + "} must have the property {field}";
}
if (!property.hasOwnProperty('reference')) {
throw "The field {" + keysObject[i] + "} must have the property {reference}";
}
if (!(property.reference instanceof Transformer)) {
throw "The field {" + keysObject[i] + ".reference} must be a instance of the Transformer";
}
}
}
this.obj = obj;
}
/**
* Method public that transform data
* @param {*} data
*/
Transformer.prototype.transformer = function (data) {
function tranformItem(properties, data) {
var dataResponse = {};
var keysObject = Object.keys(properties);
for (var i = 0; i < keysObject.length; i++) {
var key = keysObject[i];
var value = properties[key];
if (isFieldSimple(value)) {
dataResponse[key] = data[value];
}
if (isFieldFunction(value)) {
dataResponse[key] = value(data);
}
if (isFieldObject(value)) {
var field = value.field;
var reference = value.reference;
if (isFieldArray(data[value.field])) {
var collection = data[value.field];
var dataArray = [];
for (var j = 0; j < collection.length; j++) {
dataArray.push(reference.transformer(collection[j]));
}
dataResponse[key] = dataArray;
}
if (isFieldObject(data[value.field])) {
dataResponse[key] = reference.transformer(data[value.field]);
}
}
}
return dataResponse;
}
if (isFieldArray(data)) {
var dataArray = [];
for (var i = 0; i < data.length; i++) {
dataArray.push(tranformItem(this.obj, data[i]));
}
return dataArray;
}
if (isFieldObject(data)) {
return tranformItem(this.obj, data);
}
};
module.exports = exports = Transformer;