3 * Copyright(c) 2014-2015 Douglas Christopher Wilson
10 * Module dependencies.
14 var deprecate = require('depd')('body-parser')
17 * Cache of loaded parsers.
21 var parsers = Object.create(null)
26 * @property {function} json
27 * @property {function} raw
28 * @property {function} text
29 * @property {function} urlencoded
37 exports = module.exports = deprecate.function(bodyParser,
38 'bodyParser: use individual json/urlencoded middlewares')
45 Object.defineProperty(exports, 'json', {
48 get: createParserGetter('json')
56 Object.defineProperty(exports, 'raw', {
59 get: createParserGetter('raw')
67 Object.defineProperty(exports, 'text', {
70 get: createParserGetter('text')
78 Object.defineProperty(exports, 'urlencoded', {
81 get: createParserGetter('urlencoded')
85 * Create a middleware to parse json and urlencoded bodies.
87 * @param {object} [options]
93 function bodyParser (options) {
96 // exclude type option
98 for (var prop in options) {
99 if (prop !== 'type') {
100 opts[prop] = options[prop]
105 var _urlencoded = exports.urlencoded(opts)
106 var _json = exports.json(opts)
108 return function bodyParser (req, res, next) {
109 _json(req, res, function (err) {
110 if (err) return next(err)
111 _urlencoded(req, res, next)
117 * Create a getter for loading a parser.
121 function createParserGetter (name) {
122 return function get () {
123 return loadParser(name)
128 * Load a parser module.
132 function loadParser (parserName) {
133 var parser = parsers[parserName]
135 if (parser !== undefined) {
139 // this uses a switch for static require analysis
140 switch (parserName) {
142 parser = require('./lib/types/json')
145 parser = require('./lib/types/raw')
148 parser = require('./lib/types/text')
151 parser = require('./lib/types/urlencoded')
155 // store to prevent invoking require()
156 return (parsers[parserName] = parser)