-
Notifications
You must be signed in to change notification settings - Fork 57
/
index.js
216 lines (195 loc) · 5.65 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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
'use strict';
const busboy = require('busboy');
const fs = require('fs');
const os = require('os');
const path = require('path');
const getDescriptor = Object.getOwnPropertyDescriptor;
module.exports = function (request, options) {
options = options || {};
options.headers = options.headers || request.headers;
const customOnFile =
typeof options.onFile === 'function' ? options.onFile : false;
delete options.onFile;
const bb = busboy(options);
return new Promise((resolve, reject) => {
const fields = {};
const filePromises = [];
request.on('close', cleanup);
bb.on('field', onField.bind(null, fields))
.on('file', customOnFile || onFile.bind(null, filePromises))
.on('error', onError)
.on('end', onEnd)
.on('close', onEnd);
bb.on('partsLimit', function () {
const err = new Error('Reach parts limit');
err.code = 'Request_parts_limit';
err.status = 413;
onError(err);
});
bb.on('filesLimit', () => {
const err = new Error('Reach files limit');
err.code = 'Request_files_limit';
err.status = 413;
onError(err);
});
bb.on('fieldsLimit', () => {
const err = new Error('Reach fields limit');
err.code = 'Request_fields_limit';
err.status = 413;
onError(err);
});
request.pipe(bb);
function onError(err) {
cleanup();
return reject(err);
}
function onEnd(err) {
if (err) {
return reject(err);
}
if (customOnFile) {
cleanup();
resolve({ fields });
} else {
Promise.all(filePromises)
.then((files) => {
cleanup();
resolve({ fields, files });
})
.catch(reject);
}
}
function cleanup() {
bb.removeListener('field', onField);
bb.removeListener('file', customOnFile || onFile);
bb.removeListener('close', cleanup);
bb.removeListener('end', cleanup);
bb.removeListener('error', onEnd);
bb.removeListener('partsLimit', onEnd);
bb.removeListener('filesLimit', onEnd);
bb.removeListener('fieldsLimit', onEnd);
bb.removeListener('finish', onEnd);
}
});
};
/**
*
* @param {Object} fields
* @param {string} name
* @param {string} value
* @param {{ nameTruncated: boolean, valueTruncated: boolean, encoding: string, mimeType: string }} info
*/
function onField(fields, name, value, info) {
// don't overwrite prototypes
if (getDescriptor(Object.prototype, name)) return;
// This looks like a stringified array, let's parse it
if (name.indexOf('[') > -1) {
const obj = objectFromBluePrint(extractFormData(name), value);
reconcile(obj, fields);
} else {
if (fields.hasOwnProperty(name)) {
if (Array.isArray(fields[name])) {
fields[name].push(value);
} else {
fields[name] = [fields[name], value];
}
} else {
fields[name] = value;
}
}
}
/**
*
* @param {Array} filePromises
* @param {string} file
* @param {Readable} stream
* @param {{ filename: string, encoding: string, mimeType: string }} info
*/
function onFile(filePromises, file, stream, info) {
const tmpName = Math.random().toString(16).substring(2) + '-' + info.filename;
const saveTo = path.join(os.tmpdir(), path.basename(tmpName));
const writeStream = fs.createWriteStream(saveTo);
const filePromise = new Promise((resolve, reject) =>
writeStream
.on('open', () =>
stream
.pipe(writeStream)
.on('error', reject)
.on('finish', () => {
const readStream = fs.createReadStream(saveTo);
readStream.fieldname = file;
readStream.filename = info.filename;
readStream.transferEncoding = readStream.encoding = info.encoding;
readStream.mimeType = readStream.mime = info.mimeType;
resolve(readStream);
})
)
.on('error', (err) => {
stream.resume().on('error', reject);
reject(err);
})
);
filePromises.push(filePromise);
}
/**
*
* Extract a hierarchy array from a stringified formData single input.
*
*
* i.e. topLevel[sub1][sub2] => [topLevel, sub1, sub2]
*
* @param {String} string: Stringify representation of a formData Object
* @return {Array}
*
*/
const extractFormData = (string) => {
const arr = string.split('[');
const first = arr.shift();
const res = arr.map((v) => v.split(']')[0]);
res.unshift(first);
return res;
};
/**
*
* Generate an object given a hierarchy blueprint and the value
*
* i.e. [key1, key2, key3] => { key1: {key2: { key3: value }}};
*
* @param {Array} arr: from extractFormData
* @param {[type]} value: The actual value for this key
* @return {[type]} [description]
*
*/
const objectFromBluePrint = (arr, value) => {
return arr.reverse().reduce((acc, next) => {
if (Number(next).toString() === 'NaN') {
return { [next]: acc };
} else {
const newAcc = [];
newAcc[Number(next)] = acc;
return newAcc;
}
}, value);
};
/**
* Reconciles formatted data with already formatted data
*
* @param {Object} obj extractedObject
* @param {Object} target the field object
* @return {Object} reconciled fields
*
*/
const reconcile = (obj, target) => {
const key = Object.keys(obj)[0];
const val = obj[key];
// The reconciliation works even with array has
// Object.keys will yield the array indexes
// see https://jsbin.com/hulekomopo/1/
// Since array are in form of [ , , value3] [value1, value2]
// the final array will be: [value1, value2, value3] as expected
if (target.hasOwnProperty(key)) {
return reconcile(val, target[key]);
} else {
return (target[key] = val);
}
};