@splitsoftware/splitio-commons
Version:
Split JavaScript SDK common components
75 lines (74 loc) • 3.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateEvaluationOptions = exports.validateEventProperties = void 0;
var lang_1 = require("../lang");
var objectAssign_1 = require("../lang/objectAssign");
var constants_1 = require("../../logger/constants");
var ECMA_SIZES = {
NULL: 0,
STRING: 2,
BOOLEAN: 4,
NUMBER: 8
};
var MAX_PROPERTIES_AMOUNT = 300;
var MAX_EVENT_SIZE = 1024 * 32;
var BASE_EVENT_SIZE = 1024; // We assume 1kb events without properties (avg measured)
function validateEventProperties(log, maybeProperties, method) {
if (maybeProperties == undefined)
return { properties: null, size: BASE_EVENT_SIZE }; // eslint-disable-line eqeqeq
if (!(0, lang_1.isObject)(maybeProperties)) {
log.error(constants_1.ERROR_NOT_PLAIN_OBJECT, [method, 'properties']);
return { properties: false, size: BASE_EVENT_SIZE };
}
var keys = Object.keys(maybeProperties);
// Shallow clone
var clone = (0, objectAssign_1.objectAssign)({}, maybeProperties);
// To avoid calculating the size twice we'll return it from here.
var output = {
properties: clone,
size: BASE_EVENT_SIZE // We assume 1kb events without properties (avg measured)
};
if (keys.length > MAX_PROPERTIES_AMOUNT) {
log.warn(constants_1.WARN_TRIMMING_PROPERTIES, [method]);
}
for (var i = 0; i < keys.length; i++) {
output.size += keys[i].length * ECMA_SIZES.STRING; // Count the size of the key which is always a string.
var val = clone[keys[i]];
var isStringVal = (0, lang_1.isString)(val);
var isFiniteVal = (0, lang_1.isFiniteNumber)(val);
var isBoolVal = (0, lang_1.isBoolean)(val);
var isNullVal = val === null;
if (!(isStringVal || isFiniteVal || isBoolVal || isNullVal)) { // If it's not of valid type.
clone[keys[i]] = null;
val = null;
isNullVal = true;
log.warn(constants_1.WARN_SETTING_NULL, [method, keys[i]]);
}
if (isNullVal)
output.size += ECMA_SIZES.NULL;
else if (isFiniteVal)
output.size += ECMA_SIZES.NUMBER;
else if (isBoolVal)
output.size += ECMA_SIZES.BOOLEAN;
else if (isStringVal)
output.size += val.length * ECMA_SIZES.STRING;
if (output.size > MAX_EVENT_SIZE) {
log.error(constants_1.ERROR_SIZE_EXCEEDED, [method]);
output.properties = false;
break;
}
}
return output;
}
exports.validateEventProperties = validateEventProperties;
function validateEvaluationOptions(log, maybeOptions, method) {
if ((0, lang_1.isObject)(maybeOptions)) {
var properties = validateEventProperties(log, maybeOptions.properties, method).properties;
return properties && Object.keys(properties).length > 0 ? { properties: properties } : undefined;
}
else if (maybeOptions) {
log.error(constants_1.ERROR_NOT_PLAIN_OBJECT, [method, 'evaluation options']);
}
return undefined;
}
exports.validateEvaluationOptions = validateEvaluationOptions;