-
-
Notifications
You must be signed in to change notification settings - Fork 473
/
createFallbackRequestListener.ts
85 lines (76 loc) · 2.49 KB
/
createFallbackRequestListener.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
import {
Interceptor,
BatchInterceptor,
HttpRequestEventMap,
} from '@mswjs/interceptors'
import { FetchInterceptor } from '@mswjs/interceptors/lib/interceptors/fetch'
import { XMLHttpRequestInterceptor } from '@mswjs/interceptors/lib/interceptors/XMLHttpRequest'
import {
SerializedResponse,
SetupWorkerInternalContext,
StartOptions,
} from '../glossary'
import type { RequiredDeep } from '../../typeUtils'
import { handleRequest } from '../../utils/handleRequest'
import { MockedRequest } from '../../utils/request/MockedRequest'
import { serializeResponse } from '../../utils/logging/serializeResponse'
import { createResponseFromIsomorphicResponse } from '../../utils/request/createResponseFromIsomorphicResponse'
export function createFallbackRequestListener(
context: SetupWorkerInternalContext,
options: RequiredDeep<StartOptions>,
): Interceptor<HttpRequestEventMap> {
const interceptor = new BatchInterceptor({
name: 'fallback',
interceptors: [new FetchInterceptor(), new XMLHttpRequestInterceptor()],
})
interceptor.on('request', async (request) => {
const mockedRequest = new MockedRequest(request.url, {
...request,
body: await request.arrayBuffer(),
})
const response = await handleRequest<SerializedResponse>(
mockedRequest,
context.requestHandlers,
options,
context.emitter,
{
transformResponse(response) {
return {
status: response.status,
statusText: response.statusText,
headers: response.headers.all(),
body: response.body,
delay: response.delay,
}
},
onMockedResponse(_, { handler, publicRequest, parsedRequest }) {
if (!options.quiet) {
context.emitter.once('response:mocked', (response) => {
handler.log(
publicRequest,
serializeResponse(response),
parsedRequest,
)
})
}
},
},
)
if (response) {
request.respondWith(response)
}
})
interceptor.on('response', (request, response) => {
if (!request.id) {
return
}
const browserResponse = createResponseFromIsomorphicResponse(response)
if (response.headers.get('x-powered-by') === 'msw') {
context.emitter.emit('response:mocked', browserResponse, request.id)
} else {
context.emitter.emit('response:bypass', browserResponse, request.id)
}
})
interceptor.apply()
return interceptor
}