Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50654 views
1
/*!
2
* body-parser
3
* Copyright(c) 2014-2015 Douglas Christopher Wilson
4
* MIT Licensed
5
*/
6
7
'use strict'
8
9
/**
10
* Module dependencies.
11
*/
12
13
var bytes = require('bytes')
14
var contentType = require('content-type')
15
var debug = require('debug')('body-parser:text')
16
var read = require('../read')
17
var typeis = require('type-is')
18
19
/**
20
* Module exports.
21
*/
22
23
module.exports = text
24
25
/**
26
* Create a middleware to parse text bodies.
27
*
28
* @param {object} [options]
29
* @return {function}
30
* @api public
31
*/
32
33
function text (options) {
34
var opts = options || {}
35
36
var defaultCharset = opts.defaultCharset || 'utf-8'
37
var inflate = opts.inflate !== false
38
var limit = typeof opts.limit !== 'number'
39
? bytes.parse(opts.limit || '100kb')
40
: opts.limit
41
var type = opts.type || 'text/plain'
42
var verify = opts.verify || false
43
44
if (verify !== false && typeof verify !== 'function') {
45
throw new TypeError('option verify must be function')
46
}
47
48
// create the appropriate type checking function
49
var shouldParse = typeof type !== 'function'
50
? typeChecker(type)
51
: type
52
53
function parse (buf) {
54
return buf
55
}
56
57
return function textParser (req, res, next) {
58
if (req._body) {
59
debug('body already parsed')
60
next()
61
return
62
}
63
64
req.body = req.body || {}
65
66
// skip requests without bodies
67
if (!typeis.hasBody(req)) {
68
debug('skip empty body')
69
next()
70
return
71
}
72
73
debug('content-type %j', req.headers['content-type'])
74
75
// determine if request should be parsed
76
if (!shouldParse(req)) {
77
debug('skip parsing')
78
next()
79
return
80
}
81
82
// get charset
83
var charset = getCharset(req) || defaultCharset
84
85
// read
86
read(req, res, next, parse, debug, {
87
encoding: charset,
88
inflate: inflate,
89
limit: limit,
90
verify: verify
91
})
92
}
93
}
94
95
/**
96
* Get the charset of a request.
97
*
98
* @param {object} req
99
* @api private
100
*/
101
102
function getCharset (req) {
103
try {
104
return contentType.parse(req).parameters.charset.toLowerCase()
105
} catch (e) {
106
return undefined
107
}
108
}
109
110
/**
111
* Get the simple type checker.
112
*
113
* @param {string} type
114
* @return {function}
115
*/
116
117
function typeChecker (type) {
118
return function checkType (req) {
119
return Boolean(typeis(req, type))
120
}
121
}
122
123