forked from mohsen1/fb-photo-fetch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaginate.js
42 lines (34 loc) · 943 Bytes
/
paginate.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
var request = require("request");
var debug = require("debug")("api");
// walks the paginated responses to it's end an callbacks with all the results
module.exports = function(url, cb) {
var all = [];
getURL(url);
debug("getting " + url);
function getURL(url) {
request.get(url, function(err, res) {
if (err) {
return cb(err);
}
var result;
try {
result = JSON.parse(res.body);
} catch (jsonError) {
cb("Error while parsing payload. URL: " + url + " payload: ", res);
}
if (!result || !Array.isArray(result.data)) {
cb(
new Error(
"Bad response while getting " + url + " payload: " + res.body
)
);
}
all = all.concat(result.data);
if (result.paging && typeof result.paging.next === "string") {
getURL(result.paging.next);
} else {
cb(null, all);
}
});
}
};