-
-
Notifications
You must be signed in to change notification settings - Fork 481
/
onUnhandledRequest.ts
80 lines (67 loc) · 2.33 KB
/
onUnhandledRequest.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
import { toPublicUrl } from './toPublicUrl'
import { devUtils } from '../internal/devUtils'
export interface UnhandledRequestPrint {
warning(): void
error(): void
}
export type UnhandledRequestCallback = (
request: Request,
print: UnhandledRequestPrint,
) => void
export type UnhandledRequestStrategy =
| 'bypass'
| 'warn'
| 'error'
| UnhandledRequestCallback
export async function onUnhandledRequest(
request: Request,
strategy: UnhandledRequestStrategy = 'warn',
): Promise<void> {
const url = new URL(request.url)
const publicUrl = toPublicUrl(url)
const unhandledRequestMessage = `intercepted a request without a matching request handler:\n\n \u2022 ${request.method} ${publicUrl}\n\nIf you still wish to intercept this unhandled request, please create a request handler for it.\nRead more: https://mswjs.io/docs/getting-started/mocks`
function applyStrategy(strategy: UnhandledRequestStrategy) {
switch (strategy) {
case 'error': {
// Print a developer-friendly error.
devUtils.error('Error: %s', unhandledRequestMessage)
// Throw an exception to halt request processing and not perform the original request.
throw new Error(
devUtils.formatMessage(
'Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.',
),
)
}
case 'warn': {
devUtils.warn('Warning: %s', unhandledRequestMessage)
break
}
case 'bypass':
break
default:
throw new Error(
devUtils.formatMessage(
'Failed to react to an unhandled request: unknown strategy "%s". Please provide one of the supported strategies ("bypass", "warn", "error") or a custom callback function as the value of the "onUnhandledRequest" option.',
strategy,
),
)
}
}
if (typeof strategy === 'function') {
strategy(request, {
warning: applyStrategy.bind(null, 'warn'),
error: applyStrategy.bind(null, 'error'),
})
return
}
/**
* @note Ignore "file://" requests.
* Those often are an implementation detail of modern tooling
* that fetches modules via HTTP. Developers don't issue those
* requests and so they mustn't be warned about them.
*/
if (url.protocol === 'file:') {
return
}
applyStrategy(strategy)
}