-
Notifications
You must be signed in to change notification settings - Fork 44
/
_omitFields.js
116 lines (98 loc) · 2.7 KB
/
_omitFields.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
107
108
109
110
111
112
113
114
115
116
'use strict';
var argv = require('./argv');
if (!argv.omit) {
module.exports = (x) => x;
return;
}
var paths = (Array.isArray(argv.omit) ? argv.omit : [argv.omit]).map(parseStringPropertyPath);
module.exports = function (body, isFieldMap) {
isFieldMap = !!isFieldMap;
paths.forEach(function (path) {
unDefine(body, path);
});
function unDefine(obj, path) {
if (!obj) return;
var step = path.shift();
var next = obj[step];
if (path.length === 0) {
// end of the line
obj[step] = next = undefined;
}
else if (next && step === '[]') {
walkIn(next, path);
}
else if (next) {
// FIXME Make this prettier
if(isFieldMap) {
unDefine(next.properties, path);
} else {
unDefine(next, path);
}
}
path.unshift(step);
}
function walkIn(arr, path) {
if (!Array.isArray(arr)) return;
arr.forEach(function (obj) {
unDefine(obj, path);
});
}
return body;
};
//
// From lodash-deep
//
// https://github.com/marklagendijk/lodash-deep/blob/master/lodash-deep.js#L419-L474
//
/**
* Parses a string based propertyPath
* @param {string} propertyPath
* @returns {Array}
*/
function parseStringPropertyPath(propertyPath) {
var character = '';
var parsedPropertyPath = [];
var parsedPropertyPathPart = '';
var escapeNextCharacter = false;
var isSpecialCharacter = false;
var insideBrackets = false;
// Walk through the path and find backslashes that escape periods or other backslashes, and split on unescaped
// periods and brackets.
for (var i = 0; i < propertyPath.length; i++) {
character = propertyPath[i];
isSpecialCharacter = (character === '\\' || character === '[' || character === ']' || character === '.');
if (isSpecialCharacter && !escapeNextCharacter) {
if (insideBrackets && character !== ']') {
throw new SyntaxError(
'unexpected "' + character + '" within brackets at character ' +
i + ' in property path ' + propertyPath
);
}
switch (character) {
case '\\':
escapeNextCharacter = true;
break;
case ']':
insideBrackets = false;
break;
case '[':
insideBrackets = true;
/* falls through */
case '.':
parsedPropertyPath.push(parsedPropertyPathPart);
parsedPropertyPathPart = '';
break;
}
} else {
parsedPropertyPathPart += character;
escapeNextCharacter = false;
}
}
if (parsedPropertyPath[0] === '') {
//allow '[0]', or '.0'
parsedPropertyPath.splice(0, 1);
}
// capture the final part
parsedPropertyPath.push(parsedPropertyPathPart);
return parsedPropertyPath;
}