-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (68 loc) · 1.86 KB
/
index.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
'use strict';
module.exports = function(opts) {
var _flush = opts.flush;
var _flushInterval = opts.flushInterval || 60000;
var _maxRecords = opts.maxRecords || Infinity;
var _log = opts.log || _defaultLogger();
if (!_flush) {
throw new Error('You must provide a `flush` funtion to init(opts)');
}
// Will flush using this setTimeout
var _timeout;
// Contains everything that hasn't been flushed yet
var _items = [];
var self = {
push: push,
flush: flush
};
setFlushInterval();
return self;
/////
function setFlushInterval() {
clearInterval(_timeout);
if (_flushInterval < Infinity) {
_timeout = setInterval(flush, _flushInterval);
}
}
function flush(resetFlush) {
if (resetFlush) {
setFlushInterval();
}
if (_items.length === 0) {
return;
}
var curBatch = _items;
_items = [];
var res;
try {
res = _flush(curBatch);
} catch (err) {
// In case _flush is synchronous
_log.error(err, 'Error sending items');
// In case the error is transient, make sure we don't lose any logs
_items = _items.concat(curBatch);
}
if (res && res.then && res.catch) {
// Was probably a promise -- try catching and handling any errors
res.catch(function(err) {
_log.error(err, 'Error sending items');
// In case the error is transient, make sure we don't lose any logs
_items = _items.concat(curBatch);
});
}
}
function push(item) {
_items.push(item);
if (_items.length >= _maxRecords) {
// If we flushed because we reached our max items, then make sure we don't
// try to automatically flush again until the flushInterval has passed
flush(true);
}
}
function _defaultLogger() {
var noop = function() {};
return {
error: noop
};
}
};