UNPKG

948 BJavaScriptView Raw
1const _ = require('lodash');
2const qs = require('qs');
3const multiparty = require('multiparty');
4
5const RE_MIME = /^(?:multipart\/.+)$/i;
6const mime = function(req) {
7 let str = req.headers['content-type'] || '';
8 return str.split(';')[0];
9};
10
11const format = function(obj, isFiles) {
12 // Remove array for single values
13 const ret = _.mapValues(obj, value => {
14
15 // Backward compatibility (formidable)
16 if (isFiles) {
17 _.each(value, v => {v.name = v.originalFilename});
18 }
19 return value.length === 1 ? value[0] : value;
20 });
21
22 // Parse keys
23 return qs.parse(ret);
24};
25
26// Parse request with multiparty
27module.exports = function(req, res, next) {
28 if (req.method !== 'POST' || !RE_MIME.test(mime(req))) {
29 return next();
30 }
31 const form = new multiparty.Form();
32
33 form.parse(req, function(err, fields, files) {
34 req.files = format(files, true);
35 req.body = format(fields);
36 next();
37 });
38};