UNPKG

@raphaelscunha/event-tracker

Version:

A simple event tracking and user identification package with streaming capabilities

79 lines 2.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class EventTracker { constructor(config) { this.user = null; this.eventQueue = []; this.flushTimeoutId = null; this.config = { batchSize: 10, flushInterval: 5000, ...config, }; this.setupFlushInterval(); } setupFlushInterval() { if (this.flushTimeoutId) { clearInterval(this.flushTimeoutId); } this.flushTimeoutId = setInterval(() => this.flush(), this.config.flushInterval); } async identify(userId, properties) { this.user = { id: userId, properties }; await this.sendToServer('/identify', { user: this.user }); } async track(eventName, properties) { if (!this.user) { console.warn('User not identified. Please call identify() first.'); return; } const event = { name: eventName, properties, timestamp: Date.now(), }; this.eventQueue.push(event); // biome-ignore lint/style/noNonNullAssertion: <explanation> if (this.eventQueue.length >= this.config.batchSize) { await this.flush(); } } async flush() { if (this.eventQueue.length === 0) return; const eventsToSend = [...this.eventQueue]; this.eventQueue = []; await this.sendToServer('/track', { user: this.user, events: eventsToSend }); } async sendToServer(endpoint, data) { try { const response = await fetch(`${this.config.serverUrl}${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.config.apiKey}`, }, body: JSON.stringify(data), }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } } catch (error) { console.error('Failed to send data to server:', error); // If sending fails, add the events back to the queue if (endpoint === '/track' && Array.isArray(data.events)) { this.eventQueue.unshift(...data.events); } } } // Make sure to call this method when your application is closing async shutdown() { if (this.flushTimeoutId) { clearInterval(this.flushTimeoutId); } await this.flush(); } } exports.default = EventTracker; //# sourceMappingURL=index.js.map