@robotical/appv2-analytics-gatherer
Version:
A tool that gathers data from the Apps and sends it to the Analytics server
49 lines (48 loc) • 1.58 kB
JavaScript
import { sendHeartbeat } from "../core/heartbeat";
import Logger from "../services/Logger";
const SHOW_LOGS = true;
const TAG = 'Heartbeat';
class Heartbeat {
constructor({ interval, type, id, activity, screen, sessionId }) {
this.timeoutId = null;
this.interval = interval;
this.type = type;
this.isActive = false;
this.id = id;
this.activity = activity;
this.screen = screen;
this.sessionId = sessionId;
}
async start() {
if (!this.isActive) {
this.isActive = true;
const wasSent = await this.sendHeartbeat(true);
if (!wasSent) {
Logger.error(SHOW_LOGS, TAG, 'Failed to start heartbeat');
return null;
}
this.timeoutId = setInterval(() => this.sendHeartbeat(false), this.interval);
return true;
}
Logger.error(SHOW_LOGS, TAG, 'Heartbeat is already active');
return false;
}
stop(onStop) {
this.isActive = false;
if (this.timeoutId) {
clearInterval(this.timeoutId);
this.timeoutId = null;
}
if (onStop) {
onStop();
}
}
async sendHeartbeat(isNewDoc) {
const success = await sendHeartbeat({ id: this.id, isNewDoc, sessionId: this.sessionId, type: this.type, activity: this.activity, screen: this.screen });
if (!success) {
Logger.error(SHOW_LOGS, TAG, 'Heartbeat send failed');
}
return success;
}
}
export default Heartbeat;