1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | 'use strict'
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | var codes = require('./codes.json')
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | module.exports = status
|
23 |
|
24 |
|
25 | status.message = codes
|
26 |
|
27 |
|
28 | status.code = createMessageToStatusCodeMap(codes)
|
29 |
|
30 |
|
31 | status.codes = createStatusCodeList(codes)
|
32 |
|
33 |
|
34 | status.redirect = {
|
35 | 300: true,
|
36 | 301: true,
|
37 | 302: true,
|
38 | 303: true,
|
39 | 305: true,
|
40 | 307: true,
|
41 | 308: true
|
42 | }
|
43 |
|
44 |
|
45 | status.empty = {
|
46 | 204: true,
|
47 | 205: true,
|
48 | 304: true
|
49 | }
|
50 |
|
51 |
|
52 | status.retry = {
|
53 | 502: true,
|
54 | 503: true,
|
55 | 504: true
|
56 | }
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 | function createMessageToStatusCodeMap (codes) {
|
64 | var map = {}
|
65 |
|
66 | Object.keys(codes).forEach(function forEachCode (code) {
|
67 | var message = codes[code]
|
68 | var status = Number(code)
|
69 |
|
70 |
|
71 | map[message.toLowerCase()] = status
|
72 | })
|
73 |
|
74 | return map
|
75 | }
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 | function createStatusCodeList (codes) {
|
83 | return Object.keys(codes).map(function mapCode (code) {
|
84 | return Number(code)
|
85 | })
|
86 | }
|
87 |
|
88 |
|
89 |
|
90 |
|
91 |
|
92 |
|
93 | function getStatusCode (message) {
|
94 | var msg = message.toLowerCase()
|
95 |
|
96 | if (!Object.prototype.hasOwnProperty.call(status.code, msg)) {
|
97 | throw new Error('invalid status message: "' + message + '"')
|
98 | }
|
99 |
|
100 | return status.code[msg]
|
101 | }
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 |
|
108 | function getStatusMessage (code) {
|
109 | if (!Object.prototype.hasOwnProperty.call(status.message, code)) {
|
110 | throw new Error('invalid status code: ' + code)
|
111 | }
|
112 |
|
113 | return status.message[code]
|
114 | }
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 |
|
123 |
|
124 |
|
125 |
|
126 |
|
127 |
|
128 |
|
129 |
|
130 | function status (code) {
|
131 | if (typeof code === 'number') {
|
132 | return getStatusMessage(code)
|
133 | }
|
134 |
|
135 | if (typeof code !== 'string') {
|
136 | throw new TypeError('code must be a number or string')
|
137 | }
|
138 |
|
139 |
|
140 | var n = parseInt(code, 10)
|
141 | if (!isNaN(n)) {
|
142 | return getStatusMessage(n)
|
143 | }
|
144 |
|
145 | return getStatusCode(code)
|
146 | }
|