Repository navigation
Expand file tree
/
Copy pathutils.js
More file actions
81 lines (72 loc) · 2.47 KB
/
Copy pathutils.js
File metadata and controls
81 lines (72 loc) · 2.47 KB
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
var type = require('./type');
var log = function(s) {
try {
console.log('[Amplitude] ' + s);
} catch (e) {
// console logging not available
}
};
var isEmptyString = function(str) {
return (!str || str.length === 0);
};
var validateProperties = function(properties) {
var propsType = type(properties);
if (propsType !== 'object') {
log('Error: invalid event properties format. Expecting Javascript object, received ' + propsType + ', ignoring');
return {};
}
var copy = {}; // create a copy with all of the valid properties
for (var property in properties) {
if (!properties.hasOwnProperty(property)) {
continue;
}
// validate key
var key = property;
var keyType = type(key);
if (keyType !== 'string') {
log('WARNING: Non-string property key, received type ' + keyType + ', coercing to string "' + key + '"');
key = String(key);
}
// validate value
var value = validatePropertyValue(key, properties[property]);
if (value === null) {
continue;
}
copy[key] = value;
}
return copy;
};
var invalidValueTypes = [
'null', 'nan', 'undefined', 'function', 'arguments', 'regexp', 'element'
];
var validatePropertyValue = function(key, value) {
var valueType = type(value);
if (invalidValueTypes.indexOf(valueType) !== -1) {
log('WARNING: Property key "' + key + '" with invalid value type ' + valueType + ', ignoring');
value = null;
} else if (valueType === 'error') {
value = String(value);
log('WARNING: Property key "' + key + '" with value type error, coercing to ' + value);
} else if (valueType === 'array') {
// check for nested arrays or objects
var arrayCopy = [];
for (var i = 0; i < value.length; i++) {
var element = value[i];
var elemType = type(element);
if (elemType === 'array' || elemType === 'object') {
log('WARNING: Cannot have ' + elemType + ' nested in an array property value, skipping');
continue;
}
arrayCopy.push(validatePropertyValue(key, element));
}
value = arrayCopy;
} else if (valueType === 'object') {
value = validateProperties(value);
}
return value;
};
module.exports = {
log: log,
isEmptyString: isEmptyString,
validateProperties: validateProperties
};