UNPKG

@cognigy/rest-api-client

Version:

Cognigy REST-Client

41 lines 1.48 kB
"use strict"; // based on https://github.com/lyroyce/sizeof/blob/master/lib/sizeof.js Object.defineProperty(exports, "__esModule", { value: true }); exports.validateObjectSize = void 0; /** * Calculates the byte size of an object, aborts when the validation limit is hit * @param {Object} object * @param {number} limit The limit which the object cannot exceed */ const validateObjectSize = (object, limit) => { const objectList = []; const stack = [object]; let bytes = 0; while (stack.length) { const value = stack.pop(); if (typeof value === 'boolean') { bytes += 4; } else if (typeof value === 'string') { bytes += value.length * 2; } else if (typeof value === 'number') { bytes += 8; } else if (typeof value === 'object' && objectList.indexOf(value) === -1) { objectList.push(value); // if the object is not an array, add the sizes of the keys if (Object.prototype.toString.call(value) != '[object Array]') { for (const key in value) bytes += 2 * key.length; } for (const key in value) stack.push(value[key]); } if (limit && bytes > limit) return { valid: false, bytes: null }; } return { valid: true, bytes }; }; exports.validateObjectSize = validateObjectSize; //# sourceMappingURL=objectSizeValidator.js.map