/
fetch.ts
65 lines (55 loc) · 1.74 KB
/
fetch.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
import { isNodeProcess } from 'is-node-process'
import { Headers } from 'headers-polyfill'
import { MockedRequest } from '../utils/request/MockedRequest'
const useFetch: (input: RequestInfo, init?: RequestInit) => Promise<Response> =
isNodeProcess()
? (input, init) =>
import('node-fetch').then(({ default: nodeFetch }) =>
(nodeFetch as unknown as typeof window.fetch)(input, init),
)
: window.fetch
export const augmentRequestInit = (requestInit: RequestInit): RequestInit => {
const headers = new Headers(requestInit.headers)
headers.set('x-msw-bypass', 'true')
return {
...requestInit,
headers: headers.all(),
}
}
const createFetchRequestParameters = (input: MockedRequest): RequestInit => {
const { body, method } = input
const requestParameters: RequestInit = {
...input,
body: undefined,
}
if (['GET', 'HEAD'].includes(method)) {
return requestParameters
}
if (
typeof body === 'object' ||
typeof body === 'number' ||
typeof body === 'boolean'
) {
requestParameters.body = JSON.stringify(body)
} else {
requestParameters.body = body
}
return requestParameters
}
/**
* Performs a bypassed request inside a request handler.
* @example
* const originalResponse = await ctx.fetch(req)
* @see {@link https://mswjs.io/docs/api/context/fetch `ctx.fetch()`}
*/
export const fetch = (
input: string | MockedRequest,
requestInit: RequestInit = {},
): Promise<Response> => {
if (typeof input === 'string') {
return useFetch(input, augmentRequestInit(requestInit))
}
const requestParameters = createFetchRequestParameters(input)
const derivedRequestInit = augmentRequestInit(requestParameters)
return useFetch(input.url.href, derivedRequestInit)
}