raw.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*!
  2. * body-parser
  3. * Copyright(c) 2014-2015 Douglas Christopher Wilson
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module dependencies.
  8. */
  9. var bytes = require('bytes')
  10. var debug = require('debug')('body-parser:raw')
  11. var read = require('../read')
  12. var typeis = require('type-is')
  13. /**
  14. * Module exports.
  15. */
  16. module.exports = raw
  17. /**
  18. * Create a middleware to parse raw bodies.
  19. *
  20. * @param {object} [options]
  21. * @return {function}
  22. * @api public
  23. */
  24. function raw(options) {
  25. options = options || {};
  26. var inflate = options.inflate !== false
  27. var limit = typeof options.limit !== 'number'
  28. ? bytes(options.limit || '100kb')
  29. : options.limit
  30. var type = options.type || 'application/octet-stream'
  31. var verify = options.verify || false
  32. if (verify !== false && typeof verify !== 'function') {
  33. throw new TypeError('option verify must be function')
  34. }
  35. // create the appropriate type checking function
  36. var shouldParse = typeof type !== 'function'
  37. ? typeChecker(type)
  38. : type
  39. function parse(buf) {
  40. return buf
  41. }
  42. return function rawParser(req, res, next) {
  43. if (req._body) {
  44. return debug('body already parsed'), next()
  45. }
  46. req.body = req.body || {}
  47. // skip requests without bodies
  48. if (!typeis.hasBody(req)) {
  49. return debug('skip empty body'), next()
  50. }
  51. debug('content-type %s', JSON.stringify(req.headers['content-type']))
  52. // determine if request should be parsed
  53. if (!shouldParse(req)) {
  54. return debug('skip parsing'), next()
  55. }
  56. // read
  57. read(req, res, next, parse, debug, {
  58. encoding: null,
  59. inflate: inflate,
  60. limit: limit,
  61. verify: verify
  62. })
  63. }
  64. }
  65. /**
  66. * Get the simple type checker.
  67. *
  68. * @param {string} type
  69. * @return {function}
  70. */
  71. function typeChecker(type) {
  72. return function checkType(req) {
  73. return Boolean(typeis(req, type))
  74. }
  75. }