index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. // array of status codes
  19. status.codes = populateStatusesMap(status, codes)
  20. // status codes for redirects
  21. status.redirect = {
  22. 300: true,
  23. 301: true,
  24. 302: true,
  25. 303: true,
  26. 305: true,
  27. 307: true,
  28. 308: true
  29. }
  30. // status codes for empty bodies
  31. status.empty = {
  32. 204: true,
  33. 205: true,
  34. 304: true
  35. }
  36. // status codes for when you should retry the request
  37. status.retry = {
  38. 502: true,
  39. 503: true,
  40. 504: true
  41. }
  42. /**
  43. * Populate the statuses map for given codes.
  44. * @private
  45. */
  46. function populateStatusesMap (statuses, codes) {
  47. var arr = []
  48. Object.keys(codes).forEach(function forEachCode (code) {
  49. var message = codes[code]
  50. var status = Number(code)
  51. // Populate properties
  52. statuses[status] = message
  53. statuses[message] = status
  54. statuses[message.toLowerCase()] = status
  55. // Add to array
  56. arr.push(status)
  57. })
  58. return arr
  59. }
  60. /**
  61. * Get the status code.
  62. *
  63. * Given a number, this will throw if it is not a known status
  64. * code, otherwise the code will be returned. Given a string,
  65. * the string will be parsed for a number and return the code
  66. * if valid, otherwise will lookup the code assuming this is
  67. * the status message.
  68. *
  69. * @param {string|number} code
  70. * @returns {number}
  71. * @public
  72. */
  73. function status (code) {
  74. if (typeof code === 'number') {
  75. if (!status[code]) throw new Error('invalid status code: ' + code)
  76. return code
  77. }
  78. if (typeof code !== 'string') {
  79. throw new TypeError('code must be a number or string')
  80. }
  81. // '403'
  82. var n = parseInt(code, 10)
  83. if (!isNaN(n)) {
  84. if (!status[n]) throw new Error('invalid status code: ' + n)
  85. return n
  86. }
  87. n = status[code.toLowerCase()]
  88. if (!n) throw new Error('invalid status message: "' + code + '"')
  89. return n
  90. }