-
Notifications
You must be signed in to change notification settings - Fork 19
/
mapper.js
92 lines (82 loc) · 2.12 KB
/
mapper.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
var MAPPER = {}
, _ = require('underscore');
MAPPER.filterUpdate = function (maps, arg) {
/* 0: dont match
* 1: partial matching, needs more inspection
* 2: fully matching
*/
function isMatching(maps, attr, level) {
var ret = 0;
Object.keys(maps).some(function (el) {
var match;
if (attr.indexOf('.') !== -1) {
match = attr.match(new RegExp(el + "(\..*)?"));
if (match) {
ret = 2;
}
} else {
match = el === attr;
if (match) {
ret = typeof maps[el] === 'object' ? 1 : 2;
}
}
return match;
});
return ret;
}
function getObject(obj, attr) {
// dot notation
if (attr.indexOf('.') !== -1) {
return attr.split('.').reduce(function (memo, part) {
memo = memo[part];
return memo;
}, obj);
} else {
return obj[attr];
}
}
function filter(maps, el, level) {
var attr, is_matching;
for (attr in el) {
if (el.hasOwnProperty(attr)) {
// special op
if (attr[0] === '$') {
filter(maps, el[attr], level);
} else {
is_matching = isMatching(maps, attr, level);
if (is_matching === 2) {
if (Array.isArray(el[attr])) {
el[attr].forEach(function(value, i) {
el[attr][i] = getObject(maps, attr)(el[attr][i]);
});
} else {
el[attr] = getObject(maps, attr)(el[attr]);
}
} else {
if (is_matching === 1 && typeof el[attr] === 'object') {
filter(maps[attr], el[attr], level + 1);
}
}
}
}
}
}
if (!_.isEmpty(arg)) {
if (Array.isArray(arg)) {
arg.forEach(function (el) {
filter(maps, el, 0);
});
} else {
filter(maps, arg, 0);
}
}
};
MAPPER.map = function (maps, fn, args) {
if (fn === 'insert' || fn.match(/^find/)) {
MAPPER.filterUpdate(maps, args[0]);
} else if (fn === 'update') {
MAPPER.filterUpdate(maps, args[0]);
MAPPER.filterUpdate(maps, args[1]);
}
};
module.exports = MAPPER;