-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
85 lines (72 loc) · 1.81 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
const parse = require('./lib/index.js');
module.exports = function(opts = {}) {
const extendTypes = Object.assign({
json: [],
form: [],
text: [],
multipart: [],
xml: []
}, opts.extendTypes);
// default json types
const jsonTypes = [
'application/json',
...extendTypes.json
];
// default form types
const formTypes = [
'application/x-www-form-urlencoded',
...extendTypes.form
];
// default text types
const textTypes = [
'text/plain',
...extendTypes.text
];
// default multipart-form types
const multipartTypes = [
'multipart/form-data',
...extendTypes.multipart
];
// default xml types
const xmlTypes = [
'text/xml',
...extendTypes.xml
];
return function(ctx, next) {
if (ctx.request.body !== undefined) return next();
return parseBody(ctx, opts).then(body => {
if (body.raw || typeof body === 'string') {
if (ctx.request.rawBody === undefined) {
ctx.request.rawBody = body.raw || body;
}
delete body.raw;
}
ctx.request.body = body;
return next();
}, _ => {
ctx.throw(400, 'Incorrect parameter format');
});
};
function parseBody(ctx, opts) {
const methods = ['POST', 'PUT', 'DELETE', 'PATCH', 'LINK', 'UNLINK'];
if (methods.every(method => ctx.method !== method)) {
return Promise.resolve({});
}
if (ctx.request.is(jsonTypes)) {
return parse.json(ctx, opts);
}
if (ctx.request.is(formTypes)) {
return parse.form(ctx, opts);
}
if (ctx.request.is(textTypes)) {
return parse.text(ctx, opts);
}
if (ctx.request.is(multipartTypes)) {
return parse.multipart(ctx, opts);
}
if (ctx.request.is(xmlTypes)) {
return parse.xml(ctx, opts);
}
return Promise.resolve({});
}
};