-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
62 lines (50 loc) · 1.29 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const T_EMPTY_STR = ''
const T_EOL = /\r?\n/g
const T_HEADER_KEYVAL = ':'
const T_HEADER_META = ';'
const T_HEADERS_BODY = /\r?\n\r?\n/g
exports.parse = function parse(raw, boundary = null) {
if (null === boundary) {
boundary = raw.split(T_EOL)[0].trim()
}
return raw
.split(boundary)
.filter(empty)
.map(part)
.reduce(toData, {})
}
function toData(data, part) {
const { headers, body } = part
const key = headers
.filter(header => header.name === 'Content-Disposition')
.reduce((key, header) => {
return header
.value
.split(T_HEADER_META)[1]
.trim()
.match(/name="(.+)"/)[1]
}, T_EMPTY_STR)
data[key] = {
headers,
value: typeof body === 'undefined' ? '' : body.trim()
}
return data
}
function part(rawPart) {
const [rawHeaders, rawBody] = rawPart.split(T_HEADERS_BODY)
const headers = rawHeaders.split(T_EOL).filter(empty).map(header)
const body = rawBody
return { headers, body }
}
function header(rawHeader) {
const [rawName, rawValue] = rawHeader.split(T_HEADER_KEYVAL)
const name = rawName.trim()
const value = typeof rawValue === 'undefined' ? '' : rawValue.trim()
return { name, value }
}
function empty(rawPart) {
if (rawPart.trim() === T_EMPTY_STR) {
return false
}
return true
}