-
Notifications
You must be signed in to change notification settings - Fork 41
/
media-type.ts
62 lines (50 loc) · 1.45 KB
/
media-type.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
57
58
59
60
61
62
import {ReqRes} from "../types"
import Headers from "./headers"
const contentTypeParser = require("content-type")
const equals = (to: string) => (contentType: string) => to == contentType
export const jsonTypes = [
equals("application/graphql"),
equals("application/json"),
equals("application/x-amz-json-1.0"),
equals("application/x-amz-json-1.1"),
(contentType: string) => contentType.startsWith("application/") && contentType.endsWith("+json")
]
const humanReadableContentTypes = [
equals("application/javascript"),
equals("text/css"),
equals("text/html"),
equals("text/javascript"),
equals("text/plain"),
...jsonTypes
]
export default class MediaType {
private htmlReqRes: ReqRes
constructor(htmlReqRes: ReqRes) {
this.htmlReqRes = htmlReqRes
}
isHumanReadable() {
const contentType = this.contentType()
if (!contentType) {
return false
}
return humanReadableContentTypes.some(comparator => comparator(contentType))
}
isJSON() {
const contentType = this.contentType()
if (!contentType) {
return false
}
return jsonTypes.some(comparator => comparator(contentType))
}
contentType() {
const contentTypeHeader = Headers.read(this.headers(), "content-type")
if (!contentTypeHeader) {
return null
}
const parsedContentType = contentTypeParser.parse(contentTypeHeader)
return parsedContentType.type as string
}
headers() {
return this.htmlReqRes.headers
}
}