UNPKG

react-native-avo-inspector

Version:

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

76 lines (75 loc) 3.14 kB
import { AvoInspector } from "./AvoInspector"; export class AvoBatcher { constructor(networkCallsHandler) { this.events = []; this.networkCallsHandler = networkCallsHandler; this.batchFlushAttemptTimestamp = Date.now(); AvoInspector.avoStorage .getItemAsync(AvoBatcher.cacheKey) .then((savedEvents) => { if (savedEvents !== null) { const nonNullSavedEvents = savedEvents.filter((event) => event !== null); this.events = this.events.concat(nonNullSavedEvents); this.checkIfBatchNeedsToBeSent(); } }) .catch((error) => { console.error("Avo Inspector: error getting events from cache", error); }); } handleSessionStarted() { this.events.push(this.networkCallsHandler.bodyForSessionStartedCall()); this.saveEvents(); this.checkIfBatchNeedsToBeSent(); } handleTrackSchema(eventName, schema, eventId, eventHash, eventSpecMetadata) { this.events.push(this.networkCallsHandler.bodyForEventSchemaCall(eventName, schema, eventId, eventHash, eventSpecMetadata)); this.saveEvents(); if (AvoInspector.shouldLog) { console.log("Avo Inspector: saved event " + eventName + " with schema " + JSON.stringify(schema)); } this.checkIfBatchNeedsToBeSent(); } checkIfBatchNeedsToBeSent() { const batchSize = this.events.length; const now = Date.now(); const timeSinceLastFlushAttempt = now - this.batchFlushAttemptTimestamp; const sendBySize = batchSize % AvoInspector.batchSize == 0; const sendByTime = timeSinceLastFlushAttempt >= AvoInspector.batchFlushSeconds * 1000; const avoBatcher = this; if (sendBySize || sendByTime) { this.batchFlushAttemptTimestamp = now; const sendingEvents = avoBatcher.events; avoBatcher.events = []; this.networkCallsHandler.callInspectorWithBatchBody(sendingEvents, function (error) { if (error != null) { avoBatcher.events = avoBatcher.events.concat(sendingEvents); if (AvoInspector.shouldLog) { console.log("Avo Inspector: batch sending failed: " + error.message + ". We will attempt to send your schemas with next batch"); } } else { if (AvoInspector.shouldLog) { console.log("Avo Inspector: batch sent successfully."); } } avoBatcher.saveEvents(); }); } } saveEvents() { if (this.events.length > 1000) { const extraElements = this.events.length - 1000; this.events.splice(0, extraElements); } AvoInspector.avoStorage.setItem(AvoBatcher.cacheKey, this.events); } static get cacheKey() { return "AvoInspectorEvents"; } }