utils.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. }
  15. /**
  16. * Get the charset of a request.
  17. *
  18. * @param {object} req
  19. * @api private
  20. */
  21. function getCharset (req) {
  22. try {
  23. return (contentType.parse(req).parameters.charset || '').toLowerCase()
  24. } catch {
  25. return undefined
  26. }
  27. }
  28. /**
  29. * Get the simple type checker.
  30. *
  31. * @param {string | string[]} type
  32. * @return {function}
  33. */
  34. function typeChecker (type) {
  35. return function checkType (req) {
  36. return Boolean(typeis(req, type))
  37. }
  38. }
  39. /**
  40. * Normalizes the common options for all parsers.
  41. *
  42. * @param {object} options options to normalize
  43. * @param {string | string[] | function} defaultType default content type(s) or a function to determine it
  44. * @returns {object}
  45. */
  46. function normalizeOptions (options, defaultType) {
  47. if (!defaultType) {
  48. // Parsers must define a default content type
  49. throw new TypeError('defaultType must be provided')
  50. }
  51. var inflate = options?.inflate !== false
  52. var limit = typeof options?.limit !== 'number'
  53. ? bytes.parse(options?.limit || '100kb')
  54. : options?.limit
  55. var type = options?.type || defaultType
  56. var verify = options?.verify || false
  57. if (verify !== false && typeof verify !== 'function') {
  58. throw new TypeError('option verify must be function')
  59. }
  60. // create the appropriate type checking function
  61. var shouldParse = typeof type !== 'function'
  62. ? typeChecker(type)
  63. : type
  64. return {
  65. inflate,
  66. limit,
  67. verify,
  68. shouldParse
  69. }
  70. }