/
createResponse.ts
52 lines (42 loc) · 1.28 KB
/
createResponse.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import type { IncomingHttpHeaders, IncomingMessage } from 'http'
/**
* Creates a Fetch API `Response` instance from the given
* `http.IncomingMessage` instance.
*/
export function createResponse(message: IncomingMessage): Response {
const readable = new ReadableStream({
start(controller) {
message.on('data', (chunk) => controller.enqueue(chunk))
message.on('end', () => controller.close())
/**
* @todo Should also listen to the "error" on the message
* and forward it to the controller. Otherwise the stream
* will pend indefinitely.
*/
},
})
return new Response(readable, {
status: message.statusCode,
statusText: message.statusMessage,
headers: createHeadersFromIncomingHttpHeaders(message.headers),
})
}
function createHeadersFromIncomingHttpHeaders(
httpHeaders: IncomingHttpHeaders
): Headers {
const headers = new Headers()
for (const headerName in httpHeaders) {
const headerValues = httpHeaders[headerName]
if (typeof headerValues === 'undefined') {
continue
}
if (Array.isArray(headerValues)) {
headerValues.forEach((headerValue) => {
headers.append(headerName, headerValue)
})
continue
}
headers.set(headerName, headerValues)
}
return headers
}