-
-
Notifications
You must be signed in to change notification settings - Fork 473
/
streamResponse.ts
56 lines (48 loc) · 1.6 KB
/
streamResponse.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
53
54
55
56
import { invariant } from 'outvariant'
import { StrictBroadcastChannel } from '../../../utils/internal/StrictBroadcastChannel'
import {
SerializedResponse,
ServiceWorkerBroadcastChannelMessageMap,
} from '../../glossary'
import { WorkerMessageChannel } from './createMessageChannel'
export async function streamResponse(
operationChannel: StrictBroadcastChannel<ServiceWorkerBroadcastChannelMessageMap>,
messageChannel: WorkerMessageChannel,
mockedResponse: SerializedResponse,
): Promise<void> {
const response = new Response(mockedResponse.body, mockedResponse)
/**
* Delete the ReadableStream response body
* so it doesn't get sent via the message channel.
* @note Otherwise, an error: cannot clone a ReadableStream if
* it hasn't been transformed yet.
*/
delete mockedResponse.body
// Signal the mock response stream start event on the global
// message channel because the worker expects an event in response
// to the sent "REQUEST" global event.
messageChannel.send({
type: 'MOCK_RESPONSE_START',
payload: mockedResponse,
})
invariant(response.body, 'Failed to stream mocked response with no body')
// Read the mocked response body as stream
// and pipe it to the worker.
const reader = response.body.getReader()
while (true) {
const { done, value } = await reader.read()
if (!done) {
operationChannel.postMessage({
type: 'MOCK_RESPONSE_CHUNK',
payload: value,
})
continue
}
operationChannel.postMessage({
type: 'MOCK_RESPONSE_END',
})
operationChannel.close()
reader.releaseLock()
break
}
}