import { getEventObject } from './helpers' import Manager from './manager' import { Event, TracktorConfig, UserConfig } from './interfaces' export default class EventBuffer { private manager: Manager private queue: Array = [] private timerId: number | NodeJS.Timer constructor(config?: TracktorConfig) { this.manager = new Manager(config) } public push(name: string, version: number, payload: object, userConfig: UserConfig) { const failureEventDescription = `[${name}.${version}]` const { request_max_size, event_max_count, event_max_size, emit_frequency, } = this.manager.config if (Object.keys(payload).length === 0) { return this.manager.sendFailureEvent( `${failureEventDescription} No event data passed.`, userConfig ) } const event = getEventObject(name, version, payload) const eventLength = JSON.stringify(event).length if (eventLength > event_max_size) { return this.manager.sendFailureEvent( `${failureEventDescription} Pushed event exceeds allowed event size.`, userConfig ) } if (eventLength >= request_max_size - JSON.stringify(this.queue).length) { this.flush(userConfig) } this.queue.push(event) if (this.queue.length == event_max_count) { this.flush(userConfig) } // If we reach the emit frequency, initiate a flush if (!this.timerId && this.queue.length > 0) { this.timerId = setTimeout(() => { this.flush(userConfig) this.timerId = null }, emit_frequency) } } public flush(userConfig: UserConfig) { if (this.queue.length > 0) { const events: Array = this.queue.splice(0, this.manager.config.event_max_count) this.manager.send({ events }, userConfig) } } }