UNPKG

1.68 kBJavaScriptView Raw
1"use strict";
2
3const _ = require(`lodash`);
4/**
5 * Make data serializable
6 * @param {(Object|Array)} data to sanitize
7 * @param {boolean} isNode = true
8 * @param {Set<string>} path = new Set
9 */
10
11
12const 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 } // arrays and plain objects are supported - no need to to sanitize
37
38
39 return data;
40 }
41
42 if (!isTypeSupported(data)) {
43 return undefined;
44 } else {
45 return data;
46 }
47};
48/**
49 * @param {Object|Array} data
50 * @returns {Object|Array} data without undefined values
51 */
52
53
54const 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 * @param {*} data
65 * @return {boolean}
66 */
67
68
69const 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
79module.exports = sanitizeNode;
80//# sourceMappingURL=sanitize-node.js.map
\No newline at end of file