1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | 'use strict'
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | var deprecate = require('depd')('body-parser')
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | var parsers = Object.create(null)
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | exports = module.exports = deprecate.function(bodyParser,
|
38 | 'bodyParser: use individual json/urlencoded middlewares')
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 | Object.defineProperty(exports, 'json', {
|
46 | configurable: true,
|
47 | enumerable: true,
|
48 | get: createParserGetter('json')
|
49 | })
|
50 |
|
51 | /**
|
52 | * Raw parser.
|
53 | * @public
|
54 | */
|
55 |
|
56 | Object.defineProperty(exports, 'raw', {
|
57 | configurable: true,
|
58 | enumerable: true,
|
59 | get: createParserGetter('raw')
|
60 | })
|
61 |
|
62 | /**
|
63 | * Text parser.
|
64 | * @public
|
65 | */
|
66 |
|
67 | Object.defineProperty(exports, 'text', {
|
68 | configurable: true,
|
69 | enumerable: true,
|
70 | get: createParserGetter('text')
|
71 | })
|
72 |
|
73 | /**
|
74 | * URL-encoded parser.
|
75 | * @public
|
76 | */
|
77 |
|
78 | Object.defineProperty(exports, 'urlencoded', {
|
79 | configurable: true,
|
80 | enumerable: true,
|
81 | get: createParserGetter('urlencoded')
|
82 | })
|
83 |
|
84 | /**
|
85 | * Create a middleware to parse json and urlencoded bodies.
|
86 | *
|
87 | * @param {object} [options]
|
88 | * @return {function}
|
89 | * @deprecated
|
90 | * @public
|
91 | */
|
92 |
|
93 | function bodyParser (options) {
|
94 |
|
95 | var opts = Object.create(options || null, {
|
96 | type: {
|
97 | configurable: true,
|
98 | enumerable: true,
|
99 | value: undefined,
|
100 | writable: true
|
101 | }
|
102 | })
|
103 |
|
104 | var _urlencoded = exports.urlencoded(opts)
|
105 | var _json = exports.json(opts)
|
106 |
|
107 | return function bodyParser (req, res, next) {
|
108 | _json(req, res, function (err) {
|
109 | if (err) return next(err)
|
110 | _urlencoded(req, res, next)
|
111 | })
|
112 | }
|
113 | }
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 | function createParserGetter (name) {
|
121 | return function get () {
|
122 | return loadParser(name)
|
123 | }
|
124 | }
|
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 |
|
131 | function loadParser (parserName) {
|
132 | var parser = parsers[parserName]
|
133 |
|
134 | if (parser !== undefined) {
|
135 | return parser
|
136 | }
|
137 |
|
138 |
|
139 | switch (parserName) {
|
140 | case 'json':
|
141 | parser = require('./lib/types/json')
|
142 | break
|
143 | case 'raw':
|
144 | parser = require('./lib/types/raw')
|
145 | break
|
146 | case 'text':
|
147 | parser = require('./lib/types/text')
|
148 | break
|
149 | case 'urlencoded':
|
150 | parser = require('./lib/types/urlencoded')
|
151 | break
|
152 | }
|
153 |
|
154 |
|
155 | return (parsers[parserName] = parser)
|
156 | }
|