-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultipart.js
More file actions
82 lines (64 loc) · 2.28 KB
/
multipart.js
File metadata and controls
82 lines (64 loc) · 2.28 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
'use strict';
const makeHook = require('./lib/makeHook');
function multipart(app, options) {
const globalOpts = options || {};
app.extendRequest('files', undefined);
// eslint-disable-next-line no-shadow
app.extend('multipart', function multipart(expectedFiles, opts) {
const {fileLimits, requiredFiles} = formatExpectedFiles(expectedFiles);
opts = Object.assign({preservePath: globalOpts.preservePath}, opts, {
limits: Object.assign({}, globalOpts.limits, opts && opts.limits),
});
return makeHook(fileLimits, requiredFiles, opts);
});
}
function formatExpectedFiles(expectedFiles) {
if (expectedFiles === undefined) {
throw new TypeError('The `expectedFiles` option is required');
}
if (expectedFiles === 'ANY_FILES') {
return {fileLimits: null, requiredFiles: []};
}
if (typeof expectedFiles !== 'object' || expectedFiles === null) {
throw new TypeError(
'`expectedFiles` must be an object or "ANY_FILES". Received: ' + JSON.stringify(expectedFiles)
);
}
const fileLimits = {};
const requiredFiles = [];
Object.keys(expectedFiles).forEach((fieldName) => {
const file = expectedFiles[fieldName];
if (typeof file === 'number' && Number.isInteger(file)) {
fileLimits[fieldName] = file;
requiredFiles.push(fieldName);
} else if (typeof file === 'object' && file !== null) {
if (typeof file.maxCount !== 'number' || !Number.isInteger(file.maxCount)) {
throw new TypeError(
'expectedFiles object values must have a `maxCount` property that is an integer. ' +
'Received: ' + JSON.stringify(file)
);
}
fileLimits[fieldName] = file.maxCount;
if (file.optional !== true) {
requiredFiles.push(fieldName);
}
} else {
throw new TypeError(
'expectedFiles values must be an integer or an object. Received: ' + JSON.stringify(file)
);
}
});
return {fileLimits, requiredFiles};
}
multipart.discardFiles = function discardFiles(files) {
for (const fieldName in files) {
const file = files[fieldName];
if (Array.isArray(file)) {
file.forEach(f => f.stream.destroy());
} else {
file.stream.destroy();
}
}
};
multipart.MultipartError = require('./lib/MultipartError');
module.exports = multipart;