the github API sends the pagination data for the json results in the http link header:
JavaScript
x
3
1
Link: <https://api.github.com/repos?page=3&per_page=100>; rel="next",
2
<https://api.github.com/repos?page=50&per_page=100>; rel="last"
3
since the github API is not the only API using this method (i think) i wanted to ask if someone has a useful little snippet to parse the link header (and convert it to an array for example) so that i can use it for my js app.
i googled around but found nothing useful regarding how to parse pagination from json APIs
Advertisement
Answer
The parse-link-header NPM module exists for this purpose; its source can be found on github under a MIT license (free for commercial use).
Installation is as simple as:
JavaScript
1
2
1
npm install parse-link-header
2
Usage looks like the following:
JavaScript
1
3
1
var parse = require('parse-link-header');
2
var parsed = parse('<https://api.github.com/repos?page=3&per_page=100>; rel="next", <https://api.github.com/repos?page=50&per_page=100>; rel="last"')
3
…after which one has parsed.next
, parsed.last
, etc:
JavaScript
1
11
11
1
{ next:
2
{ page: '3',
3
per_page: '100',
4
rel: 'next',
5
url: 'https://api.github.com/repos?page=3&per_page=100' },
6
last:
7
{ page: '50',
8
per_page: '100',
9
rel: 'last',
10
url: ' https://api.github.com/repos?page=50&per_page=100' } }
11