-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
291 lines (249 loc) · 9.77 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
const fs = require('fs')
const os = require('os')
const path = require('path')
const {
promisify,
} = require('util')
const Busboy = require('busboy')
const sharp = require('sharp')
const createError = require('http-errors')
const {
v4: uuidv4,
} = require('uuid')
const {
includesArray,
allSettled,
createSubmitError,
unlinkWithError,
FULFILLED,
REJECTED,
} = require('./utils')
const mkdir = promisify(fs.mkdir)
const unlink = promisify(fs.unlink)
const destinationDefaultFunc = () => os.tmpdir()
const filenameDefaultFunc = () => uuidv4()
const sharpDefaultFunc = () => sharp()
module.exports = (opts = {}) => {
let {
imageFieldNames = [],
imageMaxSize,
destination: destinationFunc = destinationDefaultFunc,
filename: filenameFunc = filenameDefaultFunc,
sharp: sharpFunc = sharpDefaultFunc,
required = true,
fields,
fieldNameSize,
fieldSize,
} = opts
if (
(typeof imageFieldNames === 'string' && !imageFieldNames.length)
||
(
imageFieldNames instanceof Array &&
imageFieldNames.some(fieldName => !(fieldName + '').length)
)
) {
throw new Error('If providing, imageFieldNames must be a NOT_EMPTY string, or as array of convertables to NOT_EMPTY strings, or anything else to omit image handling')
}
let isSingleFile = true
if (imageFieldNames instanceof Array) {
isSingleFile = false
imageFieldNames = imageFieldNames.map(fieldName => fieldName + '')
} else if (imageFieldNames && typeof imageFieldNames === 'string') {
imageFieldNames = [imageFieldNames]
} else {
imageFieldNames = []
}
if (typeof destinationFunc !== 'function') {
if (typeof destinationFunc === 'string') {
const fpath = destinationFunc
destinationFunc = () => fpath
} else {
destinationFunc = destinationDefaultFunc
}
}
if (typeof filenameFunc !== 'function') {
if (typeof filenameFunc === 'string') {
const fname = filenameFunc
filenameFunc = () => fname
} else {
filenameFunc = filenameDefaultFunc
}
}
if (typeof sharpFunc !== 'function') {
sharpFunc = sharpDefaultFunc
}
if (
required instanceof Array
&&
(
required.some(fieldName => !(fieldName + '').length)
||
!includesArray(imageFieldNames, required.map(fieldName => fieldName + ''))
)
) {
throw new Error(`If provided, required must be a boolean or an array of convertables to NOT_EMPTY strings representing subset of imageFieldNames`)
}
if (required instanceof Array) {
required = required.map(fieldName => fieldName + '')
} else {
required = !!required
}
return async function (req, res, next) {
let busboy
try {
busboy = new Busboy({
headers: req.headers,
limits: {
files: imageFieldNames.length,
fileSize: imageMaxSize,
fieldNameSize,
fieldSize,
fields,
}
})
} catch {
return next(createError(400, 'Invalid headers'))
}
req.pipe(busboy)
const sendedImageFields = []
const imageOpsQueue = []
const fieldOpsQueue = []
busboy.on('file', (fieldname, file, filename, encoding, mimtype) => imageOpsQueue.push((
async () => {
const fileInfo = {
fieldname,
filename,
encoding,
mimtype,
defaultDest: destinationDefaultFunc(),
defaultFilename: filenameDefaultFunc(),
defaultSharp: sharpDefaultFunc(),
}
sendedImageFields.push(fieldname)
if (!imageFieldNames.includes(fieldname)) {
file.resume()
throw createSubmitError(`ImageField: ${fieldname} is not expected`, {
fieldname,
file: true,
})
}
let dpath, fname, fpath
try {
dpath = await destinationFunc(fileInfo)
fname = await filenameFunc(fileInfo)
await mkdir(dpath, {
recursive: true
})
fpath = path.join(dpath, fname)
} catch (err) {
file.resume()
throw createSubmitError(`Cant resolve path for file: ${fieldname}`, {
fieldname,
file: true,
originalErrMsg: err.message,
})
}
const writeFileStream = fs.createWriteStream(fpath, {
flags: 'w'
})
const writeFinished = new Promise(res => {
writeFileStream.on('finish', () => res())
writeFileStream.on('error', () => res())
})
const sharpStream = sharpFunc(fileInfo)
sharpStream.pipe(writeFileStream)
file.pipe(sharpStream)
let sizeLimitExceeded = false
file.on('limit', () => {
sizeLimitExceeded = true
})
return new Promise((res, rej) => sharpStream
.on('error', async (err) => {
await writeFinished
rej(unlinkWithError(fpath, `Bad image uploaded: ${fieldname}, originalname: ${filename}`, {
fieldname,
file: true,
originalErrMsg: err.message,
}))
})
.on('finish', async () => {
await writeFinished
if (sizeLimitExceeded) return rej(unlinkWithError(fpath, `Image size succeed limit of ${imageMaxSize} bytes: ${fieldname}, originalname: ${filename}`, {
fieldname,
file: true,
}))
// validating image
try {
// await new Promise(res => setTimeout(res, 400))
await sharp(fpath).metadata()
} catch (err) {
return rej(unlinkWithError(fpath, `Bad image uploaded: ${fieldname}, originalname: ${filename}`, {
fieldname,
originalErrMsg: err.message,
file: true,
}))
}
res({
fieldname,
filename: fname,
originalname: filename,
dist: dpath,
path: fpath,
})
}))
})())
)
busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated) => fieldOpsQueue.push((
async () => {
// if (fields instanceof Array && !fields.includes(fieldname)) {
// throw createSubmitError(`Fieldname: ${fieldname} is not expected`, {
// fieldname,
// file: false,
// })
// }
return {
fieldname,
val,
fieldnameTruncated,
valTruncated,
}
})())
)
busboy.on('finish', async () => {
const fileResults = await allSettled(imageOpsQueue)
const errors = fileResults[REJECTED]
if (isSingleFile) {
req.file = fileResults[FULFILLED].length === 1 ? fileResults[FULFILLED][0] : null
} else {
req.files = fileResults[FULFILLED]
}
const fieldResults = await allSettled(fieldOpsQueue)
req.body = fieldResults[FULFILLED].reduce((fieldsMap, field) => {
fieldsMap[field.fieldname] = field.val
return fieldsMap
}, {})
if (errors.length) {
console.log(errors)
const message = errors.reduce((message, err, index) => `${message}${index + 1}. ${err.message}\n`, '')
allSettled(fileResults.fulfilled.map(file => unlink(file.path)))
return next(createError(400, message))
}
if (required instanceof Array) {
if (!includesArray(sendedImageFields, required)) {
// const error = new Error(`Sended image fields: ${sendedImageFields} are not include all required image fields: ${required}`)
// error.sended = sendedImageFields
// error.required = required
allSettled(fileResults.fulfilled.map(file => unlink(file.path)))
return next(createError(400, `Sended image fields: ${sendedImageFields} are not include all required image fields: ${required}`))
}
} else {
if (required && !includesArray(sendedImageFields, imageFieldNames)) {
allSettled(fileResults.fulfilled.map(file => unlink(file.path)))
return next(createError(400, `Sended image fields: ${sendedImageFields} are not include all required image fields: ${imageFieldNames}`))
}
}
next()
})
}
}