forked from koajs/koa-body
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
80 lines (71 loc) · 1.83 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
/**
* koa-body - index.js
* Copyright(c) 2014
* MIT Licensed
*
* @author Daryl Lau (@dlau)
* @author Charlike Mike Reagent (@tunnckoCore)
* @api private
*/
'use strict';
/**
* Module dependencies.
*/
var buddy = require('co-body');
var forms = require('formidable');
/**
* Expose `requestbody()`.
*/
module.exports = requestbody;
/**
*
* @param {Object} options
* @see https://github.com/dlau/koa-body
* @api public
*/
function requestbody(opts) {
opts = opts || {};
opts.patchNode = 'patchNode' in opts ? opts.patchNode : false;
opts.patchKoa = 'patchKoa' in opts ? opts.patchKoa : true;
opts.multipart = 'multipart' in opts ? opts.multipart : false;
opts.encoding = 'encoding' in opts ? opts.encoding : 'utf-8';
opts.jsonLimit = 'jsonLimit' in opts ? opts.jsonLimit : '1mb';
opts.formLimit = 'formLimit' in opts ? opts.formLimit : '56kb';
opts.formidable = 'formidable' in opts ? opts.formidable : {};
return function *(next){
var body = {};
if (this.is('json')) {
body = yield buddy.json(this, {encoding: opts.encoding, limit: opts.jsonLimit});
}
else if (this.is('urlencoded')) {
body = yield buddy.form(this, {encoding: opts.encoding, limit: opts.formLimit});
}
else if (opts.multipart && this.is('multipart')) {
body = yield formy(this, opts.formidable);
}
if (opts.patchNode) {
this.req.body = body;
}
if (opts.patchKoa) {
this.request.body = body;
}
yield next;
};
};
/**
* Donable formidable
*
* @param {Stream} ctx
* @param {Object} opts
* @return {Object}
* @api private
*/
function formy(ctx, opts) {
return function(done) {
var form = new forms.IncomingForm(opts)
form.parse(ctx.req, function(err, fields, files) {
if (err) return done(err)
done(null, {fields: fields, files: files})
})
}
}