-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathpaginated_response_stream.js
53 lines (46 loc) · 1.28 KB
/
paginated_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
'use strict';
let Readable = require('stream').Readable || require('readable-stream').Readable;
class PaginatedResponseStream extends Readable {
constructor(paginatedResponse) {
super({objectMode: true});
this.paginatedResponse = paginatedResponse;
this.pageSize = 0;
this.currentPage = 0;
this.index = 0;
this.totalItems = 0;
this.items = [];
}
nextItem() {
if (this.currentPage === 0 || this.index % this.pageSize === 0 && this.index < this.totalItems) {
this.currentPage++;
this.paginatedResponse.pagingFunction(this.currentPage, (err, totalItems, pageSize, items) => {
if (err) {
this.emit('error', err);
return;
}
this.totalItems = totalItems;
this.pageSize = pageSize;
this.items = items;
this.index++;
this.push(this.items.shift());
});
} else if (this.index >= this.totalItems) {
this.push(null);
} else {
this.index++;
this.push(this.items.shift());
}
}
ready() {
this.readyToStart = true;
this.emit('ready');
}
_read() {
if (this.readyToStart) {
this.nextItem();
} else {
this.on('ready', () => this.nextItem());
}
}
}
module.exports = {PaginatedResponseStream: PaginatedResponseStream};