-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
98 lines (79 loc) · 2.27 KB
/
server.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
'use strict';
const hof = require('hof');
const config = require('./config.js');
const busboy = require('busboy');
const bl = require('bl');
const logger = require('hof/lib/logger')({ env: config.env });
const { sanitiseFilename } = require('./utils');
let settings = require('./hof.settings');
settings = Object.assign({}, settings, {
behaviours: settings.behaviours.map(require),
routes: settings.routes.map(require)
});
const app = hof(settings);
app.use((req, res, next) => {
res.locals.htmlLang = 'en';
next();
});
app.use((req, res, next) => {
if (!req.is('multipart/form-data')) {
next();
return;
}
req.files = req.files || {};
req.body = req.body || {};
const bb = busboy({
headers: req.headers,
limits: {
fileSize: config.upload.maxFileSizeInBytes
}
});
bb.on('field', (key, value) => {
req.body[key] = value;
});
bb.on('file', (key, file, fileInfo) => {
logger.info(`Processing file:
filename: ${sanitiseFilename(fileInfo.filename)},
encoding: ${fileInfo.encoding},
mimeType: ${fileInfo.mimeType}`
);
if (!fileInfo.filename) {
logger.warn(`File skipped due to missing filename for key: ${key}`);
file.resume();
return;
}
file.pipe(bl((err, data) => {
if (err) {
const errorMessage = `Failed to process file during streaming operation: ${err}`;
logger.error(errorMessage);
next(new Error(errorMessage));
return;
}
const isDataEmpty = data.length === 0;
if (isDataEmpty) {
logger.error(`Empty file received, data length: ${data.length},
filename: ${sanitiseFilename(fileInfo.filename)}`);
next(new Error('Empty file received'));
return;
}
req.files[key] = {
data: file.truncated ? null : data,
name: fileInfo.filename || null,
encoding: fileInfo.encoding,
mimetype: fileInfo.mimeType,
truncated: file.truncated,
size: Buffer.byteLength(data, 'binary')
};
}));
});
bb.on('error', err => {
const errorMessage = `Error while parsing the form: ${err}`;
logger.error(errorMessage);
return next(new Error(errorMessage));
});
bb.on('finish', () => {
next();
});
req.pipe(bb);
});
module.exports = app;