forked from keen/keen-tracking.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
defer-events.js
95 lines (83 loc) · 2.65 KB
/
defer-events.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
var Keen = require('./index');
var each = require('./utils/each');
var queue = require('./utils/queue');
module.exports = {
'deferEvent': deferEvent,
'deferEvents': deferEvents,
'queueCapacity': queueCapacity,
'queueInterval': queueInterval,
'recordDeferredEvents': recordDeferredEvents
};
function deferEvent(eventCollection, eventBody){
if (arguments.length !== 2 || typeof eventCollection !== 'string') {
handleValidationError.call(this, 'Incorrect arguments provided to #deferEvent method');
return;
}
this.queue.events[eventCollection] = this.queue.events[eventCollection] || [];
this.queue.events[eventCollection].push(eventBody);
this.queue.capacity++;
if (!this.queue.timer) {
this.queue.start();
}
this.emit('deferEvent', eventCollection, eventBody);
return this;
}
function deferEvents(eventsHash){
var self = this;
if (arguments.length !== 1 || typeof eventsHash !== 'object') {
handleValidationError.call(this, 'Incorrect arguments provided to #deferEvents method');
return;
}
each(eventsHash, function(eventList, eventCollection){
self.queue.events[eventCollection] = self.queue.events[eventCollection] || [];
self.queue.events[eventCollection] = self.queue.events[eventCollection].concat(eventList);
self.queue.capacity = self.queue.capacity + eventList.length;
if (!self.queue.timer) {
self.queue.start();
}
});
self.emit('deferEvents', eventsHash);
return self;
}
function queueCapacity(num){
if (!arguments.length) return this.queue.config.capacity;
this.queue.config.capacity = num ? Number(num): 0;
this.queue.check();
return this;
}
function queueInterval(num){
if (!arguments.length) return this.queue.config.interval;
this.queue.config.interval = num ? Number(num): 0;
this.queue.check();
return this;
}
function recordDeferredEvents(){
var self = this,
clonedQueueConfig,
clonedQueueEvents;
if (self.queue.capacity > 0) {
self.queue.pause();
clonedQueueConfig = JSON.parse(JSON.stringify(self.queue.config));
clonedQueueEvents = JSON.parse(JSON.stringify(self.queue.events));
self.queue = queue();
self.queue.config = clonedQueueConfig;
self.queue.on('flush', function(){
self.recordDeferredEvents();
});
self.emit('recordDeferredEvents', clonedQueueEvents);
self.recordEvents(clonedQueueEvents, function(err, res){
if (err) {
// Retry once
self.recordEvents(clonedQueueEvents);
}
else {
clonedQueueEvents = undefined;
}
});
}
return self;
}
function handleValidationError(message){
var err = 'Event(s) not deferred: ' + message;
this.emit('error', err);
}