1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | 'use strict'
|
8 |
|
9 |
|
10 |
|
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 |
|
21 |
|
22 |
|
23 | module.exports = text
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
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 |
|
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 |
|
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 |
|
76 | if (!shouldParse(req)) {
|
77 | debug('skip parsing')
|
78 | next()
|
79 | return
|
80 | }
|
81 |
|
82 |
|
83 | var charset = getCharset(req) || defaultCharset
|
84 |
|
85 |
|
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 |
|
97 |
|
98 |
|
99 |
|
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 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 | function typeChecker (type) {
|
118 | return function checkType (req) {
|
119 | return Boolean(typeis(req, type))
|
120 | }
|
121 | }
|