utils.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. * @returns {string | undefined}
  21. * @private
  22. */
  23. function getCharset (req) {
  24. try {
  25. return (contentType.parse(req).parameters.charset || '').toLowerCase()
  26. } catch {
  27. return undefined
  28. }
  29. }
  30. /**
  31. * Get the simple type checker.
  32. *
  33. * @param {string | string[]} type
  34. * @returns {Function}
  35. * @private
  36. */
  37. function typeChecker (type) {
  38. return function checkType (req) {
  39. return Boolean(typeis(req, type))
  40. }
  41. }
  42. /**
  43. * Normalizes the common options for all parsers.
  44. *
  45. * @param {Object} options options to normalize
  46. * @param {string | string[] | Function} defaultType default content type(s) or a function to determine it
  47. * @returns {Object}
  48. * @private
  49. */
  50. function normalizeOptions (options, defaultType) {
  51. if (!defaultType) {
  52. // Parsers must define a default content type
  53. throw new TypeError('defaultType must be provided')
  54. }
  55. var inflate = options?.inflate !== false
  56. var limit = typeof options?.limit !== 'number'
  57. ? bytes.parse(options?.limit || '100kb')
  58. : options?.limit
  59. var type = options?.type || defaultType
  60. var verify = options?.verify || false
  61. var defaultCharset = options?.defaultCharset || 'utf-8'
  62. if (verify !== false && typeof verify !== 'function') {
  63. throw new TypeError('option verify must be function')
  64. }
  65. // create the appropriate type checking function
  66. var shouldParse = typeof type !== 'function'
  67. ? typeChecker(type)
  68. : type
  69. return {
  70. inflate,
  71. limit,
  72. verify,
  73. defaultCharset,
  74. shouldParse
  75. }
  76. }
  77. /**
  78. * Passthrough function that returns input unchanged.
  79. * Used by parsers that don't need to transform the data.
  80. *
  81. * @param {*} value
  82. * @returns {*}
  83. * @private
  84. */
  85. function passthrough (value) {
  86. return value
  87. }