countly-sdk-nodejs
Version:
Countly NodeJS SDK
271 lines (263 loc) • 11.1 kB
JavaScript
/**
* main common functionalities will go in here
*/
var cc = {
// debug value from Countly
debug: false,
debugBulk: false,
debugBulkUser: false,
/**
* log level Enums:
* Error - this is a issues that needs attention right now.
* Warning - this is something that is potentially a issue. Maybe a deprecated usage of something, maybe consent is enabled but consent is not given.
* Info - All publicly exposed functions should log a call at this level to indicate that they were called. These calls should include the function name.
* Debug - this should contain logs from the internal workings of the SDK and it's important calls. This should include things like the SDK configuration options, success or fail of the current network request, "request queue is full" and the oldest request get's dropped, etc.
* Verbose - this should give a even deeper look into the SDK's inner working and should contain things that are more noisy and happen often.
*/
logLevelEnums: {
ERROR: '[ERROR] ',
WARNING: '[WARNING] ',
INFO: '[INFO] ',
DEBUG: '[DEBUG] ',
VERBOSE: '[VERBOSE] ',
},
/**
* device ID type:
* 0 - device ID was set by the developer during init
* 1 - device ID was auto generated by Countly
*/
deviceIdTypeEnums: {
DEVELOPER_SUPPLIED: 0,
SDK_GENERATED: 1,
},
/**
* At the current moment there are following internal events and their respective required consent:
* [CLY]_nps - "feedback" consent
* [CLY]_survey - "feedback" consent
* [CLY]_star_rating - "star_rating" consent
* [CLY]_view - "view" consent
* [CLY]_orientation - "users" consent
* [CLY]_push_action - "push" consent
* [CLY]_action - "clicks" or "scroll" consent
*/
internalEventKeyEnums: {
NPS: '[CLY]_nps',
SURVEY: '[CLY]_survey',
STAR_RATING: '[CLY]_star_rating',
VIEW: '[CLY]_view',
ORIENTATION: '[CLY]_orientation',
PUSH_ACTION: '[CLY]_push_action',
ACTION: '[CLY]_action',
},
storageTypeEnums: {
FILE: "file",
MEMORY: "memory",
},
/**
* Get current timestamp
* @returns {number} unix timestamp in seconds
*/
getTimestamp: function getTimestamp() {
return Math.floor(new Date().getTime() / 1000);
},
/*
* Truncates an object's key/value pairs to a certain length
* @param {Object} obj - original object to be truncated
* @param {Number} keyLimit - limit for key length
* @param {Number} valueLimit - limit for value length
* @param {Number} segmentLimit - limit for segments pairs
* @param {string} errorLog - prefix for error log
* @returns {Object} - the new truncated object
*/
truncateObject: function truncateObject(obj, keyLimit, valueLimit, segmentLimit, errorLog) {
var ob = {};
if (obj) {
if (Object.keys(obj).length > segmentLimit) {
var resizedSeg = {};
var i = 0;
for (var e in obj) {
if (i < segmentLimit) {
resizedSeg[e] = obj[e];
i++;
}
}
obj = resizedSeg;
}
for (var key in obj) {
var newKey = this.truncateSingleValue(key, keyLimit, errorLog);
var newValue = this.truncateSingleValue(obj[key], valueLimit, errorLog);
ob[newKey] = newValue;
}
}
return ob;
},
/**
* Truncates a single value to a certain length
* @param {string|number} str - original value to be truncated
* @param {Number} limit - limit length
* @param {string} errorLog - prefix for error log
* @returns {string|number} - the new truncated value
*/
truncateSingleValue: function truncateSingleValue(str, limit, errorLog) {
var newStr = str;
if (typeof str === 'number') {
str = str.toString();
}
if (typeof str === 'string') {
if (str.length > limit) {
newStr = str.substring(0, limit);
if ((this.debug || this.debugBulk || this.debugBulkUser) && typeof console !== "undefined") {
// eslint-disable-next-line no-console
console.log(`${errorLog}, Key: [${str}] is longer than accepted length. It will be truncated.`);
}
}
}
return newStr;
},
/**
* Retrieve only specific properties from object
* @param {Object} orig - object from which to get properties
* @param {Array} props - list of properties to get
* @returns {Object} Object with requested properties
*/
getProperties: function getProperties(orig, props) {
var ob = {};
var prop;
for (var i = 0; i < props.length; i++) {
prop = props[i];
if (typeof orig[prop] !== "undefined") {
ob[prop] = orig[prop];
}
}
return ob;
},
/**
* Removing trailing slashes
* @memberof Countly._internals
* @param {String} str - string from which to remove traling slash
* @returns {String} modified string
*/
stripTrailingSlash: function stripTrailingSlash(str) {
if (str.substring(str.length - 1) === "/") {
return str.substring(0, str.length - 1);
}
return str;
},
/**
* Generate random UUID value
* @returns {String} random UUID value
*/
generateUUID: function generateUUID() {
var d = new Date().getTime();
var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
},
/**
* Check if value is in UUID format
* @param {string} providedId - Id to check
* @returns {Boolean} true if it is in UUID format
*/
isUUID: function isUUID(providedId) {
return /[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-4[0-9a-fA-F]{3}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}/.test(providedId);
},
/**
* Log data if debug mode is enabled
* @param {string} level - log level (error, warning, info, debug, verbose)
* @param {string} message - any string message
*/
log: function log(level, message, ...args) {
if ((this.debug || this.debugBulk || this.debugBulkUser) && typeof console !== "undefined") {
if (args[0] && typeof args[0] === "object") {
args[0] = JSON.stringify(args[0]);
}
if (level === this.logLevelEnums.ERROR) {
// eslint-disable-next-line no-console
console.error(level + message, Array.prototype.slice.call(args).join("\n"));
}
else if (level === this.logLevelEnums.WARNING) {
// eslint-disable-next-line no-console
console.warn(level + message, Array.prototype.slice.call(args).join("\n"));
}
else if (level === this.logLevelEnums.VERBOSE) {
// eslint-disable-next-line no-console
console.log(level + message, Array.prototype.slice.call(args).join("\n"));
}
else if (level === this.logLevelEnums.INFO) {
// eslint-disable-next-line no-console
console.info(level + message, Array.prototype.slice.call(args).join("\n"));
}
else {
// default log level is DEBUG
level = this.logLevelEnums.DEBUG;
// eslint-disable-next-line no-console
console.debug(level + message, Array.prototype.slice.call(args).join("\n"));
}
}
},
/**
* Check if the http response fits the bill of:
* 1. The HTTP response code was successful (which is any 2xx code or code between 200 <= x < 300)
* 2. The returned request is a JSON object
* 3. That JSON object contains the field "result" (there can be other fields)
* @param {Number} statusCode - http incoming statusCode
* @param {String} str - response from server, ideally must be: {"result":"Success"} or should contain at least result field
* @returns {Boolean} - returns true if response passes the tests
*/
isResponseValid: function isResponseValid(statusCode, str) {
// status code and response format check
if (!(statusCode >= 200 && statusCode < 300)) {
this.log(this.logLevelEnums.ERROR, `isResponseValid, The server status code is not within the expected range: [${statusCode}]`);
return false;
}
// Try to parse JSON
try {
var response = JSON.parse(str);
if (response.result) {
// if the 'result' field exists, we return 'true'
return true;
}
// result field was not there
this.log(this.logLevelEnums.ERROR, `isResponseValid, The server response has no 'result' field`);
return false;
}
catch (e) {
this.log(this.logLevelEnums.ERROR, `isResponseValid, Http response is in the wrong format: [${e}]`);
return false;
}
},
/**
* Check if the http response fits the bill of:
* 1. The HTTP response code was successful (which is any 2xx code or code between 200 <= x < 300)
* 2. The returned request is a JSON object OR JSON array
* @param {Number} statusCode - http incoming statusCode
* @param {String} str - response from server, ideally must be: {"result":"Success"} or should contain at least result field
* @returns {Boolean} - returns true if response passes the tests
*/
isResponseValidBroad: function isResponseValidBroad(statusCode, str) {
// status code and response format check
if (!(statusCode >= 200 && statusCode < 300)) {
this.log(this.logLevelEnums.ERROR, `isResponseValidBroad, The server status code is not within the expected range: [${statusCode}]`);
return false;
}
// Try to parse JSON
try {
var response = JSON.parse(str);
// check if parsed response is a JSON object or JSON array, if not it is not valid
if ((Object.prototype.toString.call(response) !== "[object Object]") && (!Array.isArray(response))) {
this.log(this.logLevelEnums.ERROR, `isResponseValidBroad, Http response is not JSON Object nor JSON Array.`);
return false;
}
// request should be accepted even if does not have result field
return true;
}
catch (e) {
this.log(this.logLevelEnums.ERROR, `isResponseValidBroad, Http response is in the wrong format. Error: `, e);
return false;
}
},
};
module.exports = cc;