@robotical/appv2-analytics-gatherer
Version:
A tool that gathers data from the Apps and sends it to the Analytics server
63 lines (62 loc) • 2.74 kB
JavaScript
import Heartbeat from '../models/Heartbeat';
import randomHashGenerator from '../utils/randomHashGenerator';
import Logger from './Logger';
const SHOW_LOGS = true;
const TAG = 'HeartbeatsHub';
class HeartbeatsHub {
static async addHeartbeat({ interval, type, activity, screen, sessionId, }) {
const id = randomHashGenerator();
Logger.info(SHOW_LOGS, TAG, `Adding heartbeat with id: ${id} for type: ${type} and session: ${sessionId} activity: ${activity} screen: ${screen}`);
const heartbeat = new Heartbeat({ interval, type, id, activity, screen, sessionId });
const wasStarted = await heartbeat.start();
if (!wasStarted) {
Logger.error(SHOW_LOGS, TAG, `Failed to start heartbeat with id: ${id}`);
return null;
}
this.heartbeats.set(id, heartbeat);
Logger.info(SHOW_LOGS, TAG, `Heartbeat with id: ${id} started successfully`);
return id;
}
static getActiveHeartbeats() {
Logger.info(SHOW_LOGS, TAG, 'Retrieving active heartbeats');
return Array.from(this.heartbeats.values()).filter(heartbeat => heartbeat.isActive);
}
static stopAllHeartbeatsOfType(type) {
Logger.info(SHOW_LOGS, TAG, `Stopping all heartbeats of type: ${type}`);
this.heartbeats.forEach((heartbeat, id) => {
if (heartbeat.isActive && heartbeat.type === type) {
heartbeat.stop(() => {
Logger.info(SHOW_LOGS, TAG, `Heartbeat with id: ${id} stopped`);
this.heartbeats.delete(id);
Logger.info(SHOW_LOGS, TAG, `Heartbeat with id: ${id} removed`);
});
}
});
}
static stopAll() {
Logger.info(SHOW_LOGS, TAG, 'Stopping all heartbeats');
this.heartbeats.forEach((heartbeat, id) => {
heartbeat.stop(() => {
Logger.info(SHOW_LOGS, TAG, `Heartbeat with id: ${id} stopped`);
this.heartbeats.delete(id);
Logger.info(SHOW_LOGS, TAG, `Heartbeat with id: ${id} removed`);
});
});
}
static stopHeartbeat(id) {
Logger.info(SHOW_LOGS, TAG, `Stopping heartbeat with id: ${id}`);
const heartbeat = this.heartbeats.get(id);
if (heartbeat) {
heartbeat.stop(() => {
Logger.info(SHOW_LOGS, TAG, `Heartbeat with id: ${id} stopped`);
this.heartbeats.delete(id);
Logger.info(SHOW_LOGS, TAG, `Heartbeat with id: ${id} removed`);
});
}
else {
Logger.warn(SHOW_LOGS, TAG, `No heartbeat found with id: ${id}`);
}
}
}
HeartbeatsHub.heartbeats = new Map();
export default HeartbeatsHub;