-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
76 lines (67 loc) · 1.88 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
var Readable = require('stream').Readable;
var JSONStream = require('JSONStream');
var emit = require('emit-function');
var https = require('https');
var once = require('once');
var url = require('url');
module.exports = getAll;
module.exports.createReadStream = createReadStream;
function getAll(forPackage, ready) {
var all = [];
ready = once(ready);
createReadStream(forPackage, 1000)
.on('data', all.push.bind(all))
.on('error', ready)
.on('end', onend);
function onend() {
ready(null, all);
}
}
function createReadStream(forPackage, pageSize) {
pageSize = pageSize || 100;
var readable = new Readable({objectMode: true, highWaterMark: pageSize});
var page = 0;
readable._read = onread;
var requestInProgress = false;
var shouldReadMoreData = false;
return readable;
function getURLForPage(page) {
return url.format({
protocol: 'https',
host: 'skimdb.npmjs.com',
pathname: '/registry/_design/app/_view/dependedUpon',
query: {
group_level: 2,
startkey: JSON.stringify([forPackage]),
endkey: JSON.stringify([forPackage, {}]),
limit: 100,
skip: page*100,
state: 'update_after'
}
});
}
function onread(n) {
if (requestInProgress) {
shouldReadMoreData = true;
return;
}
shouldReadMoreData = false;
requestInProgress = true;
var seen = 0;
var req = https.request(getURLForPage(page++), function(res) {
res.on('error', emit(readable, 'error'));
res.pipe(JSONStream.parse('rows.*.key.1'))
.on('data', function(item) {
++seen;
if (item) readable.push(item);
})
.on('end', function() {
requestInProgress = false;
if (!seen) readable.push(null);
else if (shouldReadMoreData) onread(n);
});
});
req.on('error', emit(readable, 'error'));
req.end();
}
}