Initial commit
[yaffs-website] / node_modules / body-parser / lib / types / text.js
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       return debug('body already parsed'), next()
60     }
61
62     req.body = req.body || {}
63
64     // skip requests without bodies
65     if (!typeis.hasBody(req)) {
66       return debug('skip empty body'), next()
67     }
68
69     debug('content-type %j', req.headers['content-type'])
70
71     // determine if request should be parsed
72     if (!shouldParse(req)) {
73       return debug('skip parsing'), next()
74     }
75
76     // get charset
77     var charset = getCharset(req) || defaultCharset
78
79     // read
80     read(req, res, next, parse, debug, {
81       encoding: charset,
82       inflate: inflate,
83       limit: limit,
84       verify: verify
85     })
86   }
87 }
88
89 /**
90  * Get the charset of a request.
91  *
92  * @param {object} req
93  * @api private
94  */
95
96 function getCharset(req) {
97   try {
98     return contentType.parse(req).parameters.charset.toLowerCase()
99   } catch (e) {
100     return undefined
101   }
102 }
103
104 /**
105  * Get the simple type checker.
106  *
107  * @param {string} type
108  * @return {function}
109  */
110
111 function typeChecker(type) {
112   return function checkType(req) {
113     return Boolean(typeis(req, type))
114   }
115 }