text.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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 contentType = require('content-type')
  11. var debug = require('debug')('body-parser:text')
  12. var read = require('../read')
  13. var typeis = require('type-is')
  14. /**
  15. * Module exports.
  16. */
  17. module.exports = text
  18. /**
  19. * Create a middleware to parse text bodies.
  20. *
  21. * @param {object} [options]
  22. * @return {function}
  23. * @api public
  24. */
  25. function text(options) {
  26. options = options || {};
  27. var defaultCharset = options.defaultCharset || 'utf-8'
  28. var inflate = options.inflate !== false
  29. var limit = typeof options.limit !== 'number'
  30. ? bytes(options.limit || '100kb')
  31. : options.limit
  32. var type = options.type || 'text/plain'
  33. var verify = options.verify || false
  34. if (verify !== false && typeof verify !== 'function') {
  35. throw new TypeError('option verify must be function')
  36. }
  37. // create the appropriate type checking function
  38. var shouldParse = typeof type !== 'function'
  39. ? typeChecker(type)
  40. : type
  41. function parse(buf) {
  42. return buf
  43. }
  44. return function textParser(req, res, next) {
  45. if (req._body) {
  46. return debug('body already parsed'), next()
  47. }
  48. req.body = req.body || {}
  49. // skip requests without bodies
  50. if (!typeis.hasBody(req)) {
  51. return debug('skip empty body'), next()
  52. }
  53. debug('content-type %s', JSON.stringify(req.headers['content-type']))
  54. // determine if request should be parsed
  55. if (!shouldParse(req)) {
  56. return debug('skip parsing'), next()
  57. }
  58. // get charset
  59. var charset = getCharset(req) || defaultCharset
  60. // read
  61. read(req, res, next, parse, debug, {
  62. encoding: charset,
  63. inflate: inflate,
  64. limit: limit,
  65. verify: verify
  66. })
  67. }
  68. }
  69. /**
  70. * Get the charset of a request.
  71. *
  72. * @param {object} req
  73. * @api private
  74. */
  75. function getCharset(req) {
  76. try {
  77. return contentType.parse(req).parameters.charset.toLowerCase()
  78. } catch (e) {
  79. return undefined
  80. }
  81. }
  82. /**
  83. * Get the simple type checker.
  84. *
  85. * @param {string} type
  86. * @return {function}
  87. */
  88. function typeChecker(type) {
  89. return function checkType(req) {
  90. return Boolean(typeis(req, type))
  91. }
  92. }