How to parse link header from github API
I found wombleton/link-headers on github. It appears to be made for the browser, as opposed to being an npm module, but it seems like it wouldn't be hard to modify it to work in a server-side environment. It uses pegjs to generate a real RFC 5988 parser rather than string splits, so it should work well for any link header, rather than just Github's.
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:
npm install parse-link-header
Usage looks like the following:
var parse = require('parse-link-header');
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"')
...after which one has parsed.next
, parsed.last
, etc:
{ next:
{ page: '3',
per_page: '100',
rel: 'next',
url: 'https://api.github.com/repos?page=3&per_page=100' },
last:
{ page: '50',
per_page: '100',
rel: 'last',
url: ' https://api.github.com/repos?page=50&per_page=100' } }
There is a PageLinks class in the GitHub Java API that shows how to parse the Link
header.
I found this Gist that:
Parse Github
Links
header in JavaScript
Tested it out on the Github API and it returns an object like:
var results = {
last: "https://api.github.com/repositories/123456/issues?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&state=open&since=2013-07-24T02%3A12%3A30.309Z&direction=asc&page=4"
next: "https://api.github.com/repositories/123456/issues?access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&state=open&since=2013-07-24T02%3A12%3A30.309Z&direction=asc&page=2"
};