You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

raw.js 1.8KB

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