forked from oakserver/oak
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mediaTyper.ts
82 lines (69 loc) · 1.98 KB
/
mediaTyper.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*!
* Adapted directly from media-typer at https://github.com/jshttp/media-typer/
* which is licensed as follows:
*
* media-typer
* Copyright(c) 2014-2017 Douglas Christopher Wilson
* MIT Licensed
*/
const SUBTYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/;
const TYPE_NAME_REGEXP = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/;
const TYPE_REGEXP =
/^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/;
class MediaType {
constructor(
/** The type of the media type. */
public type: string,
/** The subtype of the media type. */
public subtype: string,
/** The optional suffix of the media type. */
public suffix?: string,
) {}
}
/** Given a media type object, return a media type string.
*
* format({
* type: "text",
* subtype: "html"
* }); // returns "text/html"
*/
export function format(obj: MediaType): string {
const { subtype, suffix, type } = obj;
if (!TYPE_NAME_REGEXP.test(type)) {
throw new TypeError("Invalid type.");
}
if (!SUBTYPE_NAME_REGEXP.test(subtype)) {
throw new TypeError("Invalid subtype.");
}
let str = `${type}/${subtype}`;
if (suffix) {
if (!TYPE_NAME_REGEXP.test(suffix)) {
throw new TypeError("Invalid suffix.");
}
str += `+${suffix}`;
}
return str;
}
/** Given a media type string, return a media type object.
*
* parse("application/json-patch+json");
* // returns {
* // type: "application",
* // subtype: "json-patch",
* // suffix: "json"
* // }
*/
export function parse(str: string): MediaType {
const match = TYPE_REGEXP.exec(str.toLowerCase());
if (!match) {
throw new TypeError("Invalid media type.");
}
let [, type, subtype] = match;
let suffix: string | undefined;
const idx = subtype.lastIndexOf("+");
if (idx !== -1) {
suffix = subtype.substr(idx + 1);
subtype = subtype.substr(0, idx);
}
return new MediaType(type, subtype, suffix);
}