-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (47 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
var continueStream = require('continue-stream')
var retryMe = require('retry-me')
var xtend = require('xtend')
var request = require('request')
var util = require('util')
module.exports = function(opts) {
if (!opts) opts = {}
if (!opts.urlFormat) throw new Error('opts.urlFormat is required')
if (!opts.end) throw new Error('opts.end is required')
var options = xtend({
start: 1,
}, opts)
var retryOptions = [
'retries',
'factor',
'minTimeout',
'maxTimeout',
'randomize'
].reduce(function(memo, key) {
if (options[key] !== undefined) memo[key] = options[key]
return memo
}, {})
var currentPage = options.start
function getStream(callback) {
var opts = xtend({
url: util.format(options.urlFormat, currentPage),
}, options)
var s = request(opts)
.on('response', function(res) {
if (res.statusCode >= 300) {
return callback(new Error('Received status code ' + res.statusCode))
}
callback(null, s)
})
.on('error', function(err) {
callback(err)
})
}
var stream = continueStream(function(callback) {
if (currentPage > options.end) return callback()
retryMe(getStream, retryOptions, function(err, s) {
callback(err, s)
currentPage++
})
})
return stream
}