forked from javascript-tutorial/server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmultipartParser.js
More file actions
executable file
·94 lines (69 loc) · 2.11 KB
/
multipartParser.js
File metadata and controls
executable file
·94 lines (69 loc) · 2.11 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
83
84
85
86
87
88
89
90
91
92
93
94
const PathListCheck = require('pathListCheck');
const multiparty = require('multiparty');
const thunkify = require('thunkify');
var log = require('log')();
function MultipartParser() {
this.ignore = new PathListCheck();
}
MultipartParser.prototype.parse = thunkify(function(req, callback) {
var form = new multiparty.Form();
var hadError = false;
var fields = {};
form.on('field', function(name, value) {
fields[name] = value;
});
// multipart file must be the last
form.on('part', function(part) {
if (part.filename !== null) {
// error is made the same way as multiparty uses
callback(createError(400, 'Files are not allowed here'));
} else {
throw new Error("Must never reach this line (field event parses all fields)");
}
part.on('error', onError);
});
form.on('error', onError);
form.on('close', onDone);
form.parse(req);
function onDone() {
log.debug("multipart parse done", fields);
if (hadError) return;
callback(null, fields);
}
function onError(err) {
log.debug("multipart error", err);
if (hadError) return;
hadError = true;
callback(err);
}
});
MultipartParser.prototype.middleware = function() {
var self = this;
return function*(next) {
// skip these methods
var contentType = this.get('content-type') || '';
if (!~['DELETE', 'POST', 'PUT', 'PATCH'].indexOf(this.method) || !contentType.startsWith('multipart/form-data')) {
return yield* next;
}
if (!self.ignore.check(this.path)) {
this.log.debug("multipart will parse");
// this may throw an error w/ status 400 or 415 or...
this.request.body = yield self.parse(this.req);
this.log.debug("multipart done parse");
} else {
this.log.debug("multipart skip");
}
yield* next;
};
};
exports.init = function(app) {
app.multipartParser = new MultipartParser();
app.use(app.multipartParser.middleware());
};
function createError(status, message) {
var error = new Error(message);
Error.captureStackTrace(error, createError);
error.status = status;
error.statusCode = status;
return error;
}