forked from myshenin/aws-lambda-multipart-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
53 lines (52 loc) · 2.28 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
function getValueIgnoringKeyCase(obj, lookedKey) {
return Object.keys(obj)
.map(presentKey => presentKey.toLowerCase() === lookedKey.toLowerCase() ? obj[presentKey] : null)
.filter(item => item)[0];
}
module.exports.parse = (event, spotText) => {
const boundary = getValueIgnoringKeyCase(event.headers, 'Content-Type').split('=')[1];
const body = (event.isBase64Encoded ? Buffer.from(event.body, 'base64').toString('binary') : event.body)
.split(boundary)
.filter(item => item.match(/Content-Disposition/))
.map((item) => {
if (item.match(/filename/)) {
const result = {};
result[
item
.match(/name="[a-zA-Z_]+([a-zA-Z0-9_]*)"/)[0]
.split('=')[1]
.match(/[a-zA-Z_]+([a-zA-Z0-9_]*)/)[0]
] = {
type: 'file',
filename: item.match(/filename="([^"]+)"/)[1],
contentType: item
.match(/Content-Type: .+\r\n\r\n/)[0]
.replace(/Content-Type: /, '')
.replace(/\r\n\r\n/, ''),
content: (spotText && item
.match(/Content-Type: .+\r\n\r\n/)[0]
.replace(/Content-Type: /, '')
.replace(/\r\n\r\n/, '')
.match(/text/)
) ? item
.split(/\r\n\r\n/)[1]
.replace(/\r\n\r\n\r\n----/, '') : Buffer.from(item
.split(/\r\n\r\n/)[1]
.replace(/\r\n\r\n\r\n----/, ''), 'binary'),
};
return result;
}
const result = {};
result[
item
.match(/name="[a-zA-Z_]+([a-zA-Z0-9_]*)"/)[0]
.split('=')[1]
.match(/[a-zA-Z_]+([a-zA-Z0-9_]*)/)[0]
] = item
.split(/\r\n\r\n/)[1]
.split(/\r\n--/)[0];
return result;
})
.reduce((accumulator, current) => Object.assign(accumulator, current), {});
return body;
};