You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.0 KiB

  1. /*!
  2. * statuses
  3. * Copyright(c) 2014 Jonathan Ong
  4. * Copyright(c) 2016 Douglas Christopher Wilson
  5. * MIT Licensed
  6. */
  7. 'use strict'
  8. /**
  9. * Module dependencies.
  10. * @private
  11. */
  12. var codes = require('./codes.json')
  13. /**
  14. * Module exports.
  15. * @public
  16. */
  17. module.exports = status
  18. // status code to message map
  19. status.STATUS_CODES = codes
  20. // array of status codes
  21. status.codes = populateStatusesMap(status, codes)
  22. // status codes for redirects
  23. status.redirect = {
  24. 300: true,
  25. 301: true,
  26. 302: true,
  27. 303: true,
  28. 305: true,
  29. 307: true,
  30. 308: true
  31. }
  32. // status codes for empty bodies
  33. status.empty = {
  34. 204: true,
  35. 205: true,
  36. 304: true
  37. }
  38. // status codes for when you should retry the request
  39. status.retry = {
  40. 502: true,
  41. 503: true,
  42. 504: true
  43. }
  44. /**
  45. * Populate the statuses map for given codes.
  46. * @private
  47. */
  48. function populateStatusesMap (statuses, codes) {
  49. var arr = []
  50. Object.keys(codes).forEach(function forEachCode (code) {
  51. var message = codes[code]
  52. var status = Number(code)
  53. // Populate properties
  54. statuses[status] = message
  55. statuses[message] = status
  56. statuses[message.toLowerCase()] = status
  57. // Add to array
  58. arr.push(status)
  59. })
  60. return arr
  61. }
  62. /**
  63. * Get the status code.
  64. *
  65. * Given a number, this will throw if it is not a known status
  66. * code, otherwise the code will be returned. Given a string,
  67. * the string will be parsed for a number and return the code
  68. * if valid, otherwise will lookup the code assuming this is
  69. * the status message.
  70. *
  71. * @param {string|number} code
  72. * @returns {number}
  73. * @public
  74. */
  75. function status (code) {
  76. if (typeof code === 'number') {
  77. if (!status[code]) throw new Error('invalid status code: ' + code)
  78. return code
  79. }
  80. if (typeof code !== 'string') {
  81. throw new TypeError('code must be a number or string')
  82. }
  83. // '403'
  84. var n = parseInt(code, 10)
  85. if (!isNaN(n)) {
  86. if (!status[n]) throw new Error('invalid status code: ' + n)
  87. return n
  88. }
  89. n = status[code.toLowerCase()]
  90. if (!n) throw new Error('invalid status message: "' + code + '"')
  91. return n
  92. }