/
create_response.js
46 lines (39 loc) · 1.32 KB
/
create_response.js
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
'use strict'
const { headersArrayToObject } = require('./common')
const { STATUS_CODES } = require('http')
/**
* Creates a Fetch API `Response` instance from the given
* `http.IncomingMessage` instance.
* Inspired by: https://github.com/mswjs/interceptors/blob/04152ed914f8041272b6e92ed374216b8177e1b2/src/interceptors/ClientRequest/utils/createResponse.ts#L8
*/
/**
* Response status codes for responses that cannot have body.
* @see https://fetch.spec.whatwg.org/#statuses
*/
const responseStatusCodesWithoutBody = [204, 205, 304]
/**
* @param {IncomingMessage} message
*/
function createResponse(message) {
const responseBodyOrNull = responseStatusCodesWithoutBody.includes(
message.statusCode,
)
? null
: 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(responseBodyOrNull, {
status: message.statusCode,
statusText: STATUS_CODES[message.statusCode],
headers: headersArrayToObject(message.rawHeaders),
})
}
module.exports = { createResponse }