-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (39 loc) · 1.39 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function parseLink(entry) {
try {
const link = entry.match(/<?([^>]*)>(.*)/),
url = link[1],
[, ...parts] = link[2].split(';'),
query = new URL(url).searchParams
const parsedLink = parts.reduce((acc, part) => {
const attr = part.match(/\s*(.+)\s*=\s*"?([^"]+)"?/)
if (attr) acc[attr[1]] = attr[2]
return acc
}, {})
for (const [key, value] of query) parsedLink[key] = value
parsedLink.url = url
return parsedLink
} catch (e) {
return null
}
}
export default function(linkHeader) {
if (!linkHeader) return null
return linkHeader.split(/,\s*</)
.map(parseLink)
.filter(link => link && link.rel)
.reduce((acc, link) => {
link.rel.split(/\s+/).forEach(rel => {
if (acc[rel] && !Array.isArray(acc[rel])) {
acc[rel] = [acc[rel]].concat(Object.assign({}, link))
acc[rel][acc[rel].length - 1].rel = rel
} else if (acc[rel] && Array.isArray(acc[rel])) {
acc[rel] = acc[rel].concat(Object.assign({}, link))
acc[rel][acc[rel].length - 1].rel = rel
} else {
acc[rel] = Object.assign({}, link)
acc[rel].rel = rel
}
})
return acc
}, {})
}