-
-
Notifications
You must be signed in to change notification settings - Fork 472
/
createRequestListener.ts
140 lines (128 loc) · 4.41 KB
/
createRequestListener.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
import {
StartOptions,
SerializedResponse,
SetupWorkerInternalContext,
ServiceWorkerIncomingEventsMap,
} from '../glossary'
import {
ServiceWorkerMessage,
WorkerChannel,
} from './utils/createMessageChannel'
import { NetworkError } from '../../utils/NetworkError'
import { parseWorkerRequest } from '../../utils/request/parseWorkerRequest'
import { handleRequest } from '../../utils/handleRequest'
import { RequiredDeep } from '../../typeUtils'
import { MockedResponse } from '../../response'
import { devUtils } from '../../utils/internal/devUtils'
import { serializeResponse } from '../../utils/logging/serializeResponse'
export const createRequestListener = (
context: SetupWorkerInternalContext,
options: RequiredDeep<StartOptions>,
) => {
return async (
event: MessageEvent,
message: ServiceWorkerMessage<
'REQUEST',
ServiceWorkerIncomingEventsMap['REQUEST']
>,
) => {
const messageChannel = new WorkerChannel(event.ports[0])
const request = parseWorkerRequest(message.payload)
try {
await handleRequest<SerializedResponse>(
request,
context.requestHandlers,
options,
context.emitter,
{
transformResponse,
onPassthroughResponse() {
messageChannel.postMessage('NOT_FOUND')
},
async onMockedResponse(
response,
{ handler, publicRequest, parsedRequest },
) {
if (response.body instanceof ReadableStream) {
throw new Error(
devUtils.formatMessage(
'Failed to construct a mocked response with a "ReadableStream" body: mocked streams are not supported. Follow https://github.com/mswjs/msw/issues/1336 for more details.',
),
)
}
const responseInstance = new Response(response.body, response)
const responseBodyBuffer = await responseInstance.arrayBuffer()
// If the mocked response has no body, keep it that way.
// Sending an empty "ArrayBuffer" to the worker will cause
// the worker constructing "new Response(new ArrayBuffer(0))"
// which will throw on responses that must have no body (i.e. 204).
const responseBody =
response.body == null ? null : responseBodyBuffer
messageChannel.postMessage(
'MOCK_RESPONSE',
{
...response,
body: responseBody,
},
[responseBodyBuffer],
)
if (!options.quiet) {
context.emitter.once('response:mocked', (response) => {
handler.log(
publicRequest,
serializeResponse(response),
parsedRequest,
)
})
}
},
},
)
} catch (error) {
if (error instanceof NetworkError) {
// Treat emulated network error differently,
// as it is an intended exception in a request handler.
messageChannel.postMessage('NETWORK_ERROR', {
name: error.name,
message: error.message,
})
return
}
if (error instanceof Error) {
devUtils.error(
`Uncaught exception in the request handler for "%s %s":
%s
This exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses`,
request.method,
request.url,
error,
)
// Treat all other exceptions in a request handler as unintended,
// alerting that there is a problem that needs fixing.
messageChannel.postMessage('MOCK_RESPONSE', {
status: 500,
statusText: 'Request Handler Error',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: error.name,
message: error.message,
stack: error.stack,
}),
})
}
}
}
}
function transformResponse(
response: MockedResponse<string>,
): SerializedResponse<string> {
return {
status: response.status,
statusText: response.statusText,
headers: response.headers.all(),
body: response.body,
delay: response.delay,
}
}