-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathsearch_response_stream.js
79 lines (63 loc) · 1.87 KB
/
search_response_stream.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
'use strict';
let Readable = require('stream').Readable || require('readable-stream').Readable;
class SearchResponseStream extends Readable {
constructor(searchResponse) {
super({objectMode: true});
this.searchResponse = searchResponse;
this.currentItem = 0;
this.currentOffset = 0;
this.bufferedResults = [];
}
nextItem() {
if (this.searchResponse.fatalError != null) {
this.emit('error', this.searchResponse.fatalError);
this.push(null);
return;
} else if (this.bufferedResults.length > 0) {
this.pushBufferedResults();
return;
} else if (this.currentItem >= this.searchResponse.ids.length) {
this.push(null);
return;
}
let index = 0;
this.searchResponse.pagingFunction(this.searchResponse.ids.slice(this.currentOffset, this.currentOffset + this.searchResponse.pageSize), (err, item) => {
if (err != null) {
this.emit('error', err);
} else {
this.bufferedResults.push(item);
}
this.currentItem += 1;
index += 1;
if (index === this.searchResponse.pageSize || this.currentItem === this.searchResponse.ids.length) {
this.push(this.bufferedResults.shift());
}
});
this.currentOffset += this.searchResponse.pageSize;
}
pushBufferedResults() {
return (() => {
let result1 = [];
while (this.bufferedResults.length > 0) {
let item;
let result = this.push(this.bufferedResults.shift());
if (result === false) { break; }
result1.push(item);
}
return result1;
})();
}
ready() {
this.readyToStart = true;
return this.emit('ready');
}
_read() {
if (this.readyToStart != null) {
return this.nextItem();
}
return this.on('ready', () => {
return this.nextItem();
});
}
}
module.exports = {SearchResponseStream: SearchResponseStream};