1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 | (function() {
|
17 | var Readable, ReadableHits, identity;
|
18 |
|
19 | ReadableHits = function(queryExec, parseHit) {
|
20 | if (!(this instanceof ReadableHits)) {
|
21 | return new ReadableHits(queryExec);
|
22 | }
|
23 | Readable.call(this, {
|
24 | objectMode: true
|
25 | });
|
26 | this.queryExec = queryExec;
|
27 | this.total = -1;
|
28 | this.from = 0;
|
29 | this._next = true;
|
30 | this._hits = [];
|
31 | this._current = 0;
|
32 | this.parseHit = parseHit || identity;
|
33 | };
|
34 |
|
35 | identity = function(hit) {
|
36 | return hit;
|
37 | };
|
38 |
|
39 | 'use strict';
|
40 |
|
41 | Readable = require('stream').Readable;
|
42 |
|
43 | module.exports = ReadableHits;
|
44 |
|
45 | ReadableHits.prototype = Object.create(Readable.prototype, {
|
46 | constructor: {
|
47 | value: ReadableHits
|
48 | }
|
49 | });
|
50 |
|
51 | ReadableHits.prototype._read = function() {
|
52 | this._current++;
|
53 | if (this._current >= this._hits.length) {
|
54 | if (!this._next) {
|
55 | return this.push(null);
|
56 | }
|
57 | this._fetchNextPage();
|
58 | } else {
|
59 | this._shift();
|
60 | }
|
61 | };
|
62 |
|
63 | ReadableHits.prototype._fetchNextPage = function() {
|
64 | var self;
|
65 | self = this;
|
66 | this.queryExec(this.from, function(e, resp) {
|
67 | self._current = 0;
|
68 | if (e) {
|
69 | self.hits = [];
|
70 | self._next = false;
|
71 | self.emit('error', e);
|
72 | return self.push(null);
|
73 | }
|
74 | self.total = resp.hits.total;
|
75 | self._hits = resp.hits.hits;
|
76 | self.from += self._hits.length;
|
77 | if (self.from >= self.total) {
|
78 | self._next = false;
|
79 | }
|
80 | if (!self._hits.length) {
|
81 | return self.push(null);
|
82 | }
|
83 | self._shift();
|
84 | });
|
85 | };
|
86 |
|
87 | ReadableHits.prototype._shift = function() {
|
88 | this.push(this.parseHit(this._hits[this._current]));
|
89 | };
|
90 |
|
91 | ReadableHits.prototype.destroy = function() {
|
92 | if (this.destroyed) {
|
93 | return;
|
94 | }
|
95 | this.destroyed = true;
|
96 | this._next = false;
|
97 | this.unpipe();
|
98 | };
|
99 |
|
100 | }).call(this);
|
101 |
|
102 |
|