UNPKG

@gleaner/tracker

Version:

A JavaScript tracking library with ecommerce support

68 lines (58 loc) 1.38 kB
import axios from 'axios'; class Emitter { /* @param {String} collector url @param {Object} collector config @param {Function (event) -> void} callback for enqueued events @param {Function (event) -> void} callback for stored events */ constructor(url, config, onEnqueued, onStored) { if (!url) { throw Error("Gleaner: collector.url must be provided") } this.config = { method: (config.method || 'post').toLowerCase(), batch: config.batch || 1, } this.onEnqueued = onEnqueued; this.onStored = onStored; // this.capacity = capacity; // this.method = method.toLowerCase(); this.queue = []; this.request = axios.create({ baseURL: url, crossDomain: true, headers: { 'content-type': 'application/json; charset=utf-8' }, }); } send() { let events = this.queue; this.queue = []; if (this.config.method === 'post') { this.request.post('/', events) .then((succ) => { events.forEach((evt) => this.onStored(evt)) }); } else { events.forEach((data) => { // TODO: use get }); } } /* Will add the item to queue. When capacity is full, it will send data to collector. @param {Object} data to send to collector */ enqueue(event) { this.queue.push(event); this.onEnqueued(event); if (this.config.batch <= this.queue.length) { this.send(); } } } export default Emitter;