forked from mongodb-js/jsonpatch-to-mongodb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
64 lines (58 loc) · 1.64 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
var toDot = require('jsonpath-to-dot');
module.exports = function(patches){
var update = {};
patches.map(function(p){
if(p.op === 'add'){
var path = toDot(p.path),
parts = path.split('.');
var key = parts[0];
var $position = parts[1] && parseInt(parts[1], 10);
update.$push = update.$push || {};
if (!isNaN($position)) {
if (update.$push[key]) {
if (!isNaN(update.$push[key].$position)) {
$position = update.$push[key].$position;
delete update.$push[key].$position;
}
if (!update.$push[key].$each) {
update.$push[key] = {
$each: [
update.$push[key]
]
};
}
update.$push[key].$each.push(p.value);
update.$push[key].$position = $position;
} else {
update.$push[key] = {
$each: [p.value],
$position: $position
};
}
} else {
if (update.$push[key]) {
if (!update.$push[key].$each) {
update.$push[key] = {
$each: [update.$push[key]]
};
}
update.$push[path].$each.push(p.value);
} else {
update.$push[path] = p.value;
}
}
}
else if(p.op === 'remove'){
if(!update.$unset) update.$unset = {};
update.$unset[toDot(p.path)] = 1;
}
else if(p.op === 'replace'){
if(!update.$set) update.$set = {};
update.$set[toDot(p.path)] = p.value;
}
else if(p.op !== 'test') {
throw new Error('Unsupported Operation! op = ' + p.op);
}
});
return update;
};