generated from freckle/npm-package-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlink-header.ts
56 lines (46 loc) · 1.32 KB
/
link-header.ts
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
45
46
47
48
49
50
51
52
53
54
55
56
import isNil from 'lodash/isNil'
export type LinkName = 'first' | 'previous' | 'next' | 'last'
export type LinkPathT = string
export function fromString(linkUrl: string): LinkPathT {
return linkUrl
}
export function toString(linkUrl: LinkPathT): string {
return linkUrl
}
export type LinksT = {
[name in LinkName]: LinkPathT
}
/* Code Imported from https://gist.github.com/niallo/3109252
* Allows us to read the Link Header and transform it in a usable object
*/
export function parseLinkHeader(linkHeader: string | null): LinksT {
if (isNil(linkHeader) || linkHeader.trim().length === 0) {
throw new Error('Expected non-zero Link header')
}
// Split parts by comma
const parts = linkHeader.split(',')
const links = {} as LinksT
// Parse each part into a named link
parts.forEach(part => {
const section = part.split(';')
if (section.length !== 2) {
return
}
const url = section[0].replace(/<(.*)>/, '$1').trim()
const rawName = section[1].replace(/rel="(.*)"/, '$1').trim()
const name = toLinkName(rawName)
links[name] = url
})
return links
}
const toLinkName = (rawName: string): LinkName => {
switch (rawName) {
case 'first':
case 'previous':
case 'next':
case 'last':
return rawName
default:
throw new Error(`Could not parse ${rawName}`)
}
}