( writeable: Duplex | ServerResponse, httpCode: keyof typeof codes, message: string | Error, contentType: contentTypes = contentTypes.text, )
| 169 | isHTTP(connection) ? !!connection.socket?.writable : !!connection.writable; |
| 170 | |
| 171 | export const writeResponse = ( |
| 172 | writeable: Duplex | ServerResponse, |
| 173 | httpCode: keyof typeof codes, |
| 174 | message: string | Error, |
| 175 | contentType: contentTypes = contentTypes.text, |
| 176 | ): void => { |
| 177 | if (!isConnected(writeable)) { |
| 178 | return; |
| 179 | } |
| 180 | |
| 181 | const isJSON = contentType.includes(contentTypes.json); |
| 182 | const isError = httpCode >= 400; |
| 183 | const httpMessage = codes[httpCode]; |
| 184 | const CTTHeader = contentType.toLowerCase().includes('charset=') |
| 185 | ? contentType |
| 186 | : `${contentType}; charset=${encodings.utf8}`; |
| 187 | const body = |
| 188 | isJSON && isError |
| 189 | ? JSON.stringify({ |
| 190 | error: message instanceof Error ? message.message : message, |
| 191 | }) |
| 192 | : message; |
| 193 | |
| 194 | if (isHTTP(writeable)) { |
| 195 | const response = writeable; |
| 196 | if (!response.headersSent) { |
| 197 | response.writeHead(httpMessage.code, { 'Content-Type': CTTHeader }); |
| 198 | response.end(body + '\n'); |
| 199 | } |
| 200 | return; |
| 201 | } |
| 202 | |
| 203 | const httpResponse = [ |
| 204 | httpMessage.message, |
| 205 | `Content-Type: ${CTTHeader}`, |
| 206 | 'Content-Encoding: UTF-8', |
| 207 | 'Accept-Ranges: bytes', |
| 208 | 'Connection: keep-alive', |
| 209 | '\r\n', |
| 210 | body, |
| 211 | ].join('\r\n'); |
| 212 | |
| 213 | writeable.write(httpResponse); |
| 214 | writeable.end(); |
| 215 | return; |
| 216 | }; |
| 217 | |
| 218 | export const jsonResponse = ( |
| 219 | response: ServerResponse, |
no test coverage detected