-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
63 lines (57 loc) · 1.72 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
63
const Busboy = require('busboy')
const getRawBody = require('raw-body')
const contentType = require('content-type')
const allowedMethods = ['POST', 'PUT']
const fileParser = ({ rawBodyOptions, busboyOptions } = {}) => [(req, res, next) => {
const type = req.headers['content-type']
if (req.rawBody === undefined && allowedMethods.includes(req.method) && type && type.startsWith('multipart/form-data')) {
getRawBody(req, Object.assign({
length: req.headers['content-length'],
limit: '10mb',
encoding: contentType.parse(req).parameters.charset,
}, rawBodyOptions), (err, rawBody) => {
if (err) next(err)
else {
req.rawBody = rawBody
next()
}
})
} else {
next()
}
}, (req, res, next) => {
const type = req.headers['content-type']
if (allowedMethods.includes(req.method) && type && type.startsWith('multipart/form-data')) {
let busboy = null
try {
busboy = new Busboy(Object.assign({ headers: req.headers }, busboyOptions))
} catch (err) {
next()
return
}
req.files = []
busboy.on('field', (fieldname, value) => {
if (!req.body) req.body = {}
req.body[fieldname] = value
})
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
let fileBuffer = Buffer.from('')
file.on('data', (data) => { fileBuffer = Buffer.concat([fileBuffer, data]) })
file.on('end', () => req.files.push({
fieldname,
originalname: filename,
encoding,
mimetype,
buffer: fileBuffer,
}))
})
busboy.on('finish', () => {
next()
})
busboy.end(req.rawBody)
} else {
next()
}
}]
module.exports = fileParser()
module.exports.fileParser = fileParser