1 | "use strict";
|
2 |
|
3 | const _ = require(`lodash`);
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const sanitizeNode = (data, isNode = true, path = new Set()) => {
|
13 | const isPlainObject = _.isPlainObject(data);
|
14 |
|
15 | if (isPlainObject || _.isArray(data)) {
|
16 | if (path.has(data)) return data;
|
17 | path.add(data);
|
18 | const returnData = isPlainObject ? {} : [];
|
19 | let anyFieldChanged = false;
|
20 |
|
21 | _.each(data, (o, key) => {
|
22 | if (isNode && key === `internal`) {
|
23 | returnData[key] = o;
|
24 | return;
|
25 | }
|
26 |
|
27 | returnData[key] = sanitizeNode(o, false, path);
|
28 |
|
29 | if (returnData[key] !== o) {
|
30 | anyFieldChanged = true;
|
31 | }
|
32 | });
|
33 |
|
34 | if (anyFieldChanged) {
|
35 | data = omitUndefined(returnData);
|
36 | }
|
37 |
|
38 |
|
39 | return data;
|
40 | }
|
41 |
|
42 | if (!isTypeSupported(data)) {
|
43 | return undefined;
|
44 | } else {
|
45 | return data;
|
46 | }
|
47 | };
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 | const omitUndefined = data => {
|
55 | const isPlainObject = _.isPlainObject(data);
|
56 |
|
57 | if (isPlainObject) {
|
58 | return _.pickBy(data, p => p !== undefined);
|
59 | }
|
60 |
|
61 | return data.filter(p => p !== undefined);
|
62 | };
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 | const isTypeSupported = data => {
|
70 | if (data === null) {
|
71 | return true;
|
72 | }
|
73 |
|
74 | const type = typeof data;
|
75 | const isSupported = type === `number` || type === `string` || type === `boolean` || data instanceof Date;
|
76 | return isSupported;
|
77 | };
|
78 |
|
79 | module.exports = sanitizeNode;
|
80 |
|
\ | No newline at end of file |