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