Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access 'rel' from Links in header? Hypermedia link relations

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.

like image 476
Þaw Avatar asked Nov 23 '17 06:11

Þaw


1 Answers

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' }
like image 130
Tarun Lalwani Avatar answered Sep 27 '22 20:09

Tarun Lalwani