-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
59 lines (49 loc) · 1.3 KB
/
index.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
'use strict';
const events = require( 'events' );
const P = require( 'bluebird' );
const Cursor = require( 'pg-cursor' );
const utils = require( './lib/utils' );
const EventEmitter = events.EventEmitter;
module.exports = ( spec ) => {
const _pgClient = spec.pg;
let _atMost = 5;
const _proto = {
atMost( numResults ) {
_atMost = numResults;
return this;
},
lazyQuery( queryText, params ) {
const cursor = _pgClient.query(
new Cursor( queryText, params )
);
function* fetcher() {
yield _performRead( cursor, _atMost );
while ( true ) {
yield _performRead( cursor, _atMost );
}
}
return () => {
const next = fetcher().next();
if ( !next.done ) {
return next.value;
} else {
const resolver = P.pending();
process.nextTick( resolver.resolve() );
return resolver.promise;
}
};
}
};
function _performRead( cursor, num ) {
const resolver = P.pending();
cursor.read( num, ( err, rows ) => {
if ( err ) {
resolver.reject( err );
} else {
resolver.resolve( rows );
}
});
return resolver.promise;
}
return utils.extend( EventEmitter, _proto );
};