utils.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use strict'
  2. /**
  3. * Module dependencies.
  4. */
  5. var bytes = require('bytes')
  6. var contentType = require('content-type')
  7. var typeis = require('type-is')
  8. /**
  9. * Module exports.
  10. */
  11. module.exports = {
  12. getCharset,
  13. normalizeOptions,
  14. passthrough
  15. }
  16. /**
  17. * Get the charset of a request.
  18. *
  19. * @param {object} req
  20. * @api private
  21. */
  22. function getCharset (req) {
  23. try {
  24. return (contentType.parse(req).parameters.charset || '').toLowerCase()
  25. } catch {
  26. return undefined
  27. }
  28. }
  29. /**
  30. * Get the simple type checker.
  31. *
  32. * @param {string | string[]} type
  33. * @return {function}
  34. */
  35. function typeChecker (type) {
  36. return function checkType (req) {
  37. return Boolean(typeis(req, type))
  38. }
  39. }
  40. /**
  41. * Normalizes the common options for all parsers.
  42. *
  43. * @param {object} options options to normalize
  44. * @param {string | string[] | function} defaultType default content type(s) or a function to determine it
  45. * @returns {object}
  46. */
  47. function normalizeOptions (options, defaultType) {
  48. if (!defaultType) {
  49. // Parsers must define a default content type
  50. throw new TypeError('defaultType must be provided')
  51. }
  52. var inflate = options?.inflate !== false
  53. var limit = typeof options?.limit !== 'number'
  54. ? bytes.parse(options?.limit || '100kb')
  55. : options?.limit
  56. var type = options?.type || defaultType
  57. var verify = options?.verify || false
  58. var defaultCharset = options?.defaultCharset || 'utf-8'
  59. if (verify !== false && typeof verify !== 'function') {
  60. throw new TypeError('option verify must be function')
  61. }
  62. // create the appropriate type checking function
  63. var shouldParse = typeof type !== 'function'
  64. ? typeChecker(type)
  65. : type
  66. return {
  67. inflate,
  68. limit,
  69. verify,
  70. defaultCharset,
  71. shouldParse
  72. }
  73. }
  74. /**
  75. * Passthrough function that returns input unchanged.
  76. * Used by parsers that don't need to transform the data.
  77. *
  78. * @param {*} value
  79. * @return {*}
  80. */
  81. function passthrough (value) {
  82. return value
  83. }