-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfetch.ts
23 lines (19 loc) · 836 Bytes
/
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
/**
* Global fetch interceptor.
*/
import { matchSchemas } from '../request-matcher/utils';
import { ResponseBuilder } from '../response-builder';
import { extractMockSchemas, GetHeaders } from '../transport';
export function setupFetchInterceptor(getIncomingHeaders: GetHeaders) {
const originalFetch = globalThis.fetch;
globalThis.fetch = async (input, init) => {
const request = new Request(input, init);
const mockSchemas = await extractMockSchemas(getIncomingHeaders);
const matchResult = await matchSchemas(request, mockSchemas);
if (!matchResult) return originalFetch(input, init);
const { body, headers, status, statusText } = await new ResponseBuilder(matchResult, {
bypass: (req) => originalFetch(req),
}).build();
return new Response(body, { status, statusText, headers });
};
}