UNPKG

avo-inspector

Version:

[![npm version](https://badge.fury.io/js/avo-inspector.svg)](https://badge.fury.io/js/avo-inspector)

83 lines (82 loc) 3.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AvoBatcher = void 0; var AvoInspector_1 = require("./AvoInspector"); var AvoBatcher = /** @class */ (function () { function AvoBatcher(networkCallsHandler) { var _this = this; this.events = []; this.networkCallsHandler = networkCallsHandler; this.batchFlushAttemptTimestamp = Date.now(); AvoInspector_1.AvoInspector.avoStorage .getItemAsync(AvoBatcher.cacheKey) .then(function (savedEvents) { if (savedEvents !== null) { var nonNullSavedEvents = savedEvents.filter(function (event) { return event !== null; }); _this.events = _this.events.concat(nonNullSavedEvents); _this.checkIfBatchNeedsToBeSent(); } }); } AvoBatcher.prototype.handleSessionStarted = function () { this.events.push(this.networkCallsHandler.bodyForSessionStartedCall()); this.saveEvents(); this.checkIfBatchNeedsToBeSent(); }; AvoBatcher.prototype.handleTrackSchema = function (eventName, schema, eventId, eventHash) { this.events.push(this.networkCallsHandler.bodyForEventSchemaCall(eventName, schema, eventId, eventHash)); this.saveEvents(); if (AvoInspector_1.AvoInspector.shouldLog) { console.log("Avo Inspector: saved event " + eventName + " with schema " + JSON.stringify(schema)); } this.checkIfBatchNeedsToBeSent(); }; AvoBatcher.prototype.checkIfBatchNeedsToBeSent = function () { var batchSize = this.events.length; var now = Date.now(); var timeSinceLastFlushAttempt = now - this.batchFlushAttemptTimestamp; var sendBySize = batchSize % AvoInspector_1.AvoInspector.batchSize == 0; var sendByTime = timeSinceLastFlushAttempt >= AvoInspector_1.AvoInspector.batchFlushSeconds * 1000; var avoBatcher = this; if (sendBySize || sendByTime) { this.batchFlushAttemptTimestamp = now; var sendingEvents_1 = avoBatcher.events; avoBatcher.events = []; this.networkCallsHandler.callInspectorWithBatchBody(sendingEvents_1, function (error) { if (error != null) { avoBatcher.events = avoBatcher.events.concat(sendingEvents_1); if (AvoInspector_1.AvoInspector.shouldLog) { console.log("Avo Inspector: batch sending failed: " + error + ". We will attempt to send your schemas with next batch"); } } else { if (AvoInspector_1.AvoInspector.shouldLog) { console.log("Avo Inspector: batch sent successfully."); } } avoBatcher.saveEvents(); }); } }; AvoBatcher.prototype.saveEvents = function () { if (this.events.length > 1000) { var extraElements = this.events.length - 1000; this.events.splice(0, extraElements); } AvoInspector_1.AvoInspector.avoStorage.setItem(AvoBatcher.cacheKey, this.events); }; Object.defineProperty(AvoBatcher, "cacheKey", { get: function () { return "AvoInspectorEvents"; }, enumerable: false, configurable: true }); return AvoBatcher; }()); exports.AvoBatcher = AvoBatcher;