utils.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. 'use strict'
  2. /**
  3. * Module dependencies.
  4. */
  5. const bytes = require('bytes')
  6. const contentType = require('content-type')
  7. const 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. * @returns {string | undefined}
  21. * @private
  22. */
  23. function getCharset (req) {
  24. const header = req.headers['content-type']
  25. if (!header) return undefined
  26. return contentType.parse(header).parameters.charset?.toLowerCase()
  27. }
  28. /**
  29. * Get the simple type checker.
  30. *
  31. * @param {string | string[]} type
  32. * @returns {Function}
  33. * @private
  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. * @private
  47. */
  48. function normalizeOptions (options, defaultType) {
  49. if (!defaultType) {
  50. // Parsers must define a default content type
  51. throw new TypeError('defaultType must be provided')
  52. }
  53. const inflate = options?.inflate !== false
  54. const limit = typeof options?.limit === 'undefined' || options?.limit === null
  55. ? 102400 // 100kb default
  56. : bytes.parse(options.limit)
  57. const type = options?.type || defaultType
  58. const verify = options?.verify || false
  59. const defaultCharset = options?.defaultCharset || 'utf-8'
  60. if (limit === null) {
  61. throw new TypeError(`option limit "${String(options.limit)}" is invalid`)
  62. }
  63. if (verify !== false && typeof verify !== 'function') {
  64. throw new TypeError('option verify must be function')
  65. }
  66. // create the appropriate type checking function
  67. const shouldParse = typeof type !== 'function'
  68. ? typeChecker(type)
  69. : type
  70. return {
  71. inflate,
  72. limit,
  73. verify,
  74. defaultCharset,
  75. shouldParse
  76. }
  77. }
  78. /**
  79. * Passthrough function that returns input unchanged.
  80. * Used by parsers that don't need to transform the data.
  81. *
  82. * @param {*} value
  83. * @returns {*}
  84. * @private
  85. */
  86. function passthrough (value) {
  87. return value
  88. }