index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*!
  2. * body-parser
  3. * Copyright(c) 2014 Douglas Christopher Wilson
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module dependencies.
  8. */
  9. var deprecate = require('depd')('body-parser')
  10. var fs = require('fs')
  11. var path = require('path')
  12. /**
  13. * @typedef Parsers
  14. * @type {function}
  15. * @property {function} json
  16. * @property {function} raw
  17. * @property {function} text
  18. * @property {function} urlencoded
  19. */
  20. /**
  21. * Module exports.
  22. * @type {Parsers}
  23. */
  24. exports = module.exports = deprecate.function(bodyParser,
  25. 'bodyParser: use individual json/urlencoded middlewares')
  26. /**
  27. * Path to the parser modules.
  28. */
  29. var parsersDir = path.join(__dirname, 'lib', 'types')
  30. /**
  31. * Auto-load bundled parsers with getters.
  32. */
  33. fs.readdirSync(parsersDir).forEach(function onfilename(filename) {
  34. if (!/\.js$/.test(filename)) return
  35. var loc = path.resolve(parsersDir, filename)
  36. var mod
  37. var name = path.basename(filename, '.js')
  38. function load() {
  39. if (mod) {
  40. return mod
  41. }
  42. return mod = require(loc)
  43. }
  44. Object.defineProperty(exports, name, {
  45. configurable: true,
  46. enumerable: true,
  47. get: load
  48. })
  49. })
  50. /**
  51. * Create a middleware to parse json and urlencoded bodies.
  52. *
  53. * @param {object} [options]
  54. * @return {function}
  55. * @deprecated
  56. * @api public
  57. */
  58. function bodyParser(options){
  59. var opts = {}
  60. options = options || {}
  61. // exclude type option
  62. for (var prop in options) {
  63. if ('type' !== prop) {
  64. opts[prop] = options[prop]
  65. }
  66. }
  67. var _urlencoded = exports.urlencoded(opts)
  68. var _json = exports.json(opts)
  69. return function bodyParser(req, res, next) {
  70. _json(req, res, function(err){
  71. if (err) return next(err);
  72. _urlencoded(req, res, next);
  73. });
  74. }
  75. }