3 * Copyright(c) 2014-2015 Douglas Christopher Wilson
10 * Module dependencies.
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')
26 * Create a middleware to parse text bodies.
28 * @param {object} [options]
33 function text (options) {
34 var opts = options || {}
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')
41 var type = opts.type || 'text/plain'
42 var verify = opts.verify || false
44 if (verify !== false && typeof verify !== 'function') {
45 throw new TypeError('option verify must be function')
48 // create the appropriate type checking function
49 var shouldParse = typeof type !== 'function'
53 function parse (buf) {
57 return function textParser (req, res, next) {
59 debug('body already parsed')
64 req.body = req.body || {}
66 // skip requests without bodies
67 if (!typeis.hasBody(req)) {
68 debug('skip empty body')
73 debug('content-type %j', req.headers['content-type'])
75 // determine if request should be parsed
76 if (!shouldParse(req)) {
83 var charset = getCharset(req) || defaultCharset
86 read(req, res, next, parse, debug, {
96 * Get the charset of a request.
102 function getCharset (req) {
104 return (contentType.parse(req).parameters.charset || '').toLowerCase()
111 * Get the simple type checker.
113 * @param {string} type
117 function typeChecker (type) {
118 return function checkType (req) {
119 return Boolean(typeis(req, type))