1 | export default function parseLinkHeader(link) {
|
2 | const parsed = [];
|
3 | const items = link.split(',');
|
4 | for (const item of items) {
|
5 |
|
6 | const [rawUriReference, ...rawLinkParameters] = item.split(';');
|
7 | const trimmedUriReference = rawUriReference.trim();
|
8 |
|
9 | if (trimmedUriReference[0] !== '<' || trimmedUriReference.at(-1) !== '>') {
|
10 | throw new Error(`Invalid format of the Link header reference: ${trimmedUriReference}`);
|
11 | }
|
12 | const reference = trimmedUriReference.slice(1, -1);
|
13 | const parameters = {};
|
14 | if (rawLinkParameters.length === 0) {
|
15 | throw new Error(`Unexpected end of Link header parameters: ${rawLinkParameters.join(';')}`);
|
16 | }
|
17 | for (const rawParameter of rawLinkParameters) {
|
18 | const trimmedRawParameter = rawParameter.trim();
|
19 | const center = trimmedRawParameter.indexOf('=');
|
20 | if (center === -1) {
|
21 | throw new Error(`Failed to parse Link header: ${link}`);
|
22 | }
|
23 | const name = trimmedRawParameter.slice(0, center).trim();
|
24 | const value = trimmedRawParameter.slice(center + 1).trim();
|
25 | parameters[name] = value;
|
26 | }
|
27 | parsed.push({
|
28 | reference,
|
29 | parameters,
|
30 | });
|
31 | }
|
32 | return parsed;
|
33 | }
|