1 | # request-all-pages [![build status](https://secure.travis-ci.org/thlorenz/request-all-pages.png)](http://travis-ci.org/thlorenz/request-all-pages)
|
2 |
|
3 | Requests all pages of paginated data and emits them into a stream or aggregates them into an array.
|
4 |
|
5 | Follows the [link headers](http://tools.ietf.org/html/rfc5988) until it reaches the last page. As an example see [github
|
6 | api pagination](http://developer.github.com/v3/#pagination)
|
7 |
|
8 |
|
9 | ```js
|
10 | var requestAllPages = require('request-all-pages');
|
11 |
|
12 | var opts = {
|
13 | uri: 'https://api.github.com/users/substack/repos'
|
14 | , json: true
|
15 | , body: {}
|
16 | , headers: { 'user-agent': 'request-all-pages' }
|
17 | }
|
18 | , startPage = 1
|
19 | , pagesPer = 100;
|
20 |
|
21 | requestAllPages(opts, startPage, pagesPer, function (err, pages) {
|
22 | if (err) return console.error(err);
|
23 | var names = pages
|
24 | .reduce(
|
25 | function (acc, page) {
|
26 | acc = acc.concat(page.body.map(function (repo) { return repo.name; }))
|
27 | return acc;
|
28 | }
|
29 | , []);
|
30 |
|
31 | console.log('%s\nTotal: %s', names.join(', '), names.length);
|
32 | });
|
33 | ```
|
34 |
|
35 | ```js
|
36 | // same using streaming interface
|
37 | requestAllPages(opts, startPage, pagesPer)
|
38 | .on('error', console.error)
|
39 | .pipe(through(
|
40 | function (data) {
|
41 | var page = JSON.parse(data)
|
42 | , names = page.body.map(function (repo) { return repo.name; });
|
43 | this.queue(names.join(', '));
|
44 | }
|
45 | ))
|
46 | .pipe(process.stdout);
|
47 | ```
|
48 |
|
49 | ```
|
50 | airport, airport-cluster-example, amok-copter, astw, ....
|
51 | ```
|
52 |
|
53 | ## Installation
|
54 |
|
55 | npm install request-all-pages
|
56 |
|
57 | ## API
|
58 |
|
59 | ***requestAllPages(opts : Object, startPage : Number, perPage: Number[, callback : Function]) : Stream***
|
60 |
|
61 | - **opts**: options passed to [request](https://github.com/mikeal/request) after the `uri` was modified to
|
62 | include paging information. The same opts will be used for all paging requests.
|
63 | - **startPage**: the page to start at
|
64 | - **perPage**: how many pages to ask for per request (the smaller this number, the more requests have to be made to get
|
65 | all data)
|
66 | - **callback**: `function (err, pages) {..}` if supplied, it will be called with an error or an array containing all
|
67 | pages each with the following structure ( `{ headers: /* response headers */, body: /* response body */ }`)
|
68 |
|
69 | If **no callback** is supplied, a `stream` is returned instead which emits `data` for each page and `error` if one
|
70 | occurs.
|