10

I am using json server and axios

result from header

link: "<http://localhost:3001/posts?_page=1>; rel="first", <http://localhost:3001/posts?_page=2>; rel="next", <http://localhost:3001/posts?_page=5>; rel="last""

How can I use/access these data from link? There seems to be no information about how to parse or access this aside from github. I tried link.rels[:last] like from github but it doesnt work.

Þaw
  • 2,047
  • 4
  • 22
  • 39

2 Answers2

7

Since JS is quite flexible you can simply use

data = 'link: "<http://localhost:3001/posts?_page=1>; rel="first", <http://localhost:3001/posts?_page=2>; rel="next", <http://localhost:3001/posts?_page=5>; rel="last""'

function parseData(data) {
    let arrData = data.split("link:")
    data = arrData.length == 2? arrData[1]: data;
    let parsed_data = {}

    arrData = data.split(",")

    for (d of arrData){
        linkInfo = /<([^>]+)>;\s+rel="([^"]+)"/ig.exec(d)

        parsed_data[linkInfo[2]]=linkInfo[1]
    }

    return parsed_data;
}

console.log(parseData(data))

The output is

{ first: 'http://localhost:3001/posts?_page=1',
  next: 'http://localhost:3001/posts?_page=2',
  last: 'http://localhost:3001/posts?_page=5' }
Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265
0

var data = 'link: "<http://localhost:3001/posts?_page=1>; rel="first", <http://localhost:3001/posts?_page=2>; rel="next", <http://localhost:3001/posts?_page=5>; rel="last""'

var linkRegex = /\<([^>]+)/g;
var relRegex = /rel="([^"]+)/g;
var linkArray = [];
var relArray = [];
var finalResult = {};
var temp;
while ((temp = linkRegex.exec(data)) != null) {
    linkArray.push(temp[1]);
}
while ((temp = relRegex.exec(data)) != null) {
    relArray.push(temp[1]);
}

finalResult = relArray.reduce((object, value, index) => {
    object[value] = linkArray[index];
    return object;
}, {});

console.log(finalResult);
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29