index.js
2.6 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**!
* koa-body-parser - index.js
* Copyright(c) 2014
* MIT Licensed
*
* Authors:
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
* fengmk2 <m@fengmk2.com> (http://fengmk2.com)
*/
'use strict';
/**
* Module dependencies.
*/
const parse = require('co-body');
/**
* @param [Object] opts
* - {String} jsonLimit default '1mb'
* - {String} formLimit default '56kb'
* - {string} encoding default 'utf-8'
* - {Object} extendTypes
*/
module.exports = function (opts) {
opts = opts || {};
const detectJSON = opts.detectJSON;
const onerror = opts.onerror || throwError;
const enableTypes = opts.enableTypes || ['json', 'form'];
const enableForm = checkEnable(enableTypes, 'form');
const enableJson = checkEnable(enableTypes, 'json');
const enableText = checkEnable(enableTypes, 'text');
opts.detectJSON = undefined;
opts.onerror = undefined;
// default json types
const jsonTypes = [
'application/json',
'application/json-patch+json',
'application/vnd.api+json',
'application/csp-report',
];
// default form types
const formTypes = [
'application/x-www-form-urlencoded',
];
// default text types
const textTypes = [
'text/plain',
];
const jsonOpts = formatOptions(opts, 'json');
const formOpts = formatOptions(opts, 'form');
const textOpts = formatOptions(opts, 'text');
const extendTypes = opts.extendTypes || {};
extendType(jsonTypes, extendTypes.json);
extendType(formTypes, extendTypes.form);
extendType(textTypes, extendTypes.text);
return function bodyParser(ctx, next) {
if (ctx.request.body !== undefined) return next();
return parseBody(ctx).then(body => {
ctx.request.body = body;
return next();
}, err => onerror(err, ctx));
};
function parseBody(ctx) {
if (enableJson && ((detectJSON && detectJSON(ctx)) || ctx.request.is(jsonTypes))) {
return parse.json(ctx, jsonOpts);
}
if (enableForm && ctx.request.is(formTypes)) {
return parse.form(ctx, formOpts);
}
if (enableText && ctx.request.is(textTypes)) {
return parse.text(ctx, textOpts) || '';
}
return Promise.resolve({});
}
};
function formatOptions(opts, type) {
var res = {};
Object.assign(res, opts);
res.limit = opts[type + 'Limit'];
return res;
}
function extendType(original, extend) {
if (extend) {
if (!Array.isArray(extend)) {
extend = [extend];
}
extend.forEach(extend => original.push(extend));
}
}
function throwError(err) {
throw err;
}
function checkEnable(types, type) {
return types.indexOf(type) >= 0;
}