-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
130 lines (106 loc) · 2.87 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"use strict";
const multipart = require('connect-multiparty');
const fse = require('fs-extra');
const fs = require('fs');
const onExit = require('signal-exit');
const formData = {};
function autoClean(files, onExitRemover) {
const clean = [];
format(files, (file) => {
file instanceof fs.ReadStream && file.destroy && file.destroy();
if(typeof file != 'object' || typeof file.path != 'string') {
return null;
}
clean.push(new Promise((resolve, reject) => {
fse.remove(file.path).then(resolve).catch(err => {
err.code == 'ENOENT'? resolve(): reject(err);
});
}));
return file;
});
Promise.all(clean)
.finally(() => onExitRemover && onExitRemover())
.catch(err => console.warn(err.stack));
}
function cleanSync(files) {
format(files, (file) => {
file instanceof fs.ReadStream && file.destroy && file.destroy();
if(typeof file != 'object' || typeof file.path != 'string') {
return;
}
try {
fse.removeSync(file.path);
}
catch(err) {
console.warn(err.stack);
}
});
}
function format (obj, fn) {
for(let k in obj) {
if(Array.isArray(obj[k])) {
for(let i = 0, l = obj[k].length; i < l; i++) {
obj[k][i] = fn(obj[k][i]);
if(!obj[k][i]) {
obj[k].splice(i, 1);
}
}
if(!obj[k].length) {
delete obj[k];
}
}
else if(
obj[k] &&
typeof obj[k] == 'object' &&
!obj[k].hasOwnProperty('originalFilename') &&
!(obj[k] instanceof fs.ReadStream)
) {
format(obj[k], fn);
if(!Object.keys(obj[k]).length) {
delete obj[k];
}
}
else {
obj[k] = fn(obj[k]);
if(!obj[k]) {
delete obj[k];
}
}
}
}
formData.parse = function (options) {
return function (req, res, next) {
if(options && options.autoClean) {
const onExitRemover = onExit(() => cleanSync(req.files));
req.on('close', () => autoClean(req.files, onExitRemover));
res.on('finish', () => autoClean(req.files, onExitRemover));
}
return multipart(options).apply(this, arguments);
}
};
formData.format = function () {
return function (req, res, next) {
const clean = [];
format(req.files, obj => {
if(obj.size <= 0) {
clean.push(fse.remove(obj.path));
return null;
}
return obj;
});
Promise.all(clean).then(() => next()).catch(next);
};
};
formData.stream = function () {
return function (req, res, next) {
format(req.files, obj => fs.createReadStream(obj.path));
next();
};
};
formData.union = function () {
return function (req, res, next) {
Object.assign(req.body, req.files);
next();
};
};
module.exports = formData;