-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbulk.js
56 lines (49 loc) · 1.32 KB
/
bulk.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
const _ = require('lodash');
/**
* Class representing a batch executor
* @param {number} max size of batch
* @param {number} timeout in ms
* @param {function} batchFunc function to be called
* @returns
*/
module.exports = function (size, timeout, batchFunc) {
let batch = [];
let counter = 0;
// Create an executor function
const execBatchFunc = async () => {
// Reset the batch
const tmp = batch;
batch = [];
// Process the batch
await batchFunc(tmp);
counter += tmp.length;
console.log(`Processed ${tmp.length} records`);
};
// Create a throttled executor function
const throttledFunc = _.throttle(execBatchFunc, timeout, {
leading: false,
trailing: true,
});
return {
/**
* Push item to batch
* @param {any} item
*/
push(item) {
batch.push(item);
if (batch.length >= size) {
// Flush the batch when the batch is full
this.flush();
} else {
// Run the throttled function when the batch is not full
throttledFunc();
}
},
async flush() {
return throttledFunc.flush();
},
getCounter() {
return counter;
},
};
};