UNPKG

1.2 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const stream_1 = require("stream");
4const WAIT_THRESHOLD = 500;
5class BatchStream extends stream_1.Transform {
6 constructor(options = {}) {
7 super();
8 this.bufferedBatch = null;
9 this.timeout = null;
10 this.waitThreshold = 0;
11 this.waitThreshold = options.wait || WAIT_THRESHOLD;
12 }
13 flush() {
14 if (this.bufferedBatch) {
15 this.push(this.bufferedBatch);
16 this.bufferedBatch = null;
17 }
18 if (this.timeout) {
19 clearTimeout(this.timeout);
20 this.timeout = null;
21 }
22 }
23 _transform(chunk, encoding, callback) {
24 if (this.bufferedBatch) {
25 this.bufferedBatch = Buffer.concat([this.bufferedBatch, chunk]);
26 }
27 else {
28 this.bufferedBatch = chunk;
29 }
30 if (this.timeout) {
31 clearTimeout(this.timeout);
32 }
33 this.timeout = setTimeout(() => {
34 this.flush();
35 }, this.waitThreshold);
36 callback();
37 }
38 _flush(callback) {
39 this.flush();
40 callback();
41 }
42}
43exports.default = BatchStream;