Skip to content

Instantly share code, notes, and snippets.

@niallo
Created July 14, 2012 04:54
Show Gist options
  • Save niallo/3109252 to your computer and use it in GitHub Desktop.
Save niallo/3109252 to your computer and use it in GitHub Desktop.
Parse Github `Links` header in JavaScript
/*
* parse_link_header()
*
* Parse the Github Link HTTP header used for pageination
* http://developer.github.com/v3/#pagination
*/
function parse_link_header(header) {
if (header.length == 0) {
throw new Error("input must not be of zero length");
}
// Split parts by comma
var parts = header.split(',');
var links = {};
// Parse each part into a named link
_.each(parts, function(p) {
var section = p.split(';');
if (section.length != 2) {
throw new Error("section could not be split on ';'");
}
var url = section[0].replace(/<(.*)>/, '$1').trim();
var name = section[1].replace(/rel="(.*)"/, '$1').trim();
links[name] = url;
});
return links;
}
@tillkruss
Copy link

Lodash:

const links = _.chain(link)
        .split(',')
        .map(link => {
          return {
            ref: link.split(';')[1].replace(/rel="(.*)"/, '$1').trim(),
            url: link.split(';')[0].replace(/<(.*)>/, '$1').trim(),
          }
        })
        .keyBy('ref')
        .mapValues('url')
        .value()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment