-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.js
52 lines (43 loc) · 1.25 KB
/
parser.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
'use strict';
const Busboy = require('busboy');
const getContentType = (event) => {
let contentType = event.headers['content-type']
if (!contentType){
return event.headers['Content-Type'];
}
return contentType;
};
const parser = (event) => new Promise((resolve, reject) => {
const busboy = new Busboy({
headers: {
'content-type': getContentType(event),
}
});
let result = {
files: []
};
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
file.on('data', data => {
result.files.push({
file: data,
fileName: filename,
contentType: mimetype
});
});
});
busboy.on('field', (fieldname, value) => {
try {
result[fieldname] = JSON.parse(value);
} catch (err) {
result[fieldname] = value;
}
});
busboy.on('error', error => reject(`Parse error: ${error}`));
busboy.on('finish', () => {
event.body = result;
resolve(event);
});
busboy.write(event.body, event.isBase64Encoded ? 'base64' : 'binary');
busboy.end();
});
module.exports.parse = parser;