blob: 71031c58424592fdb07f4802c97603e7fba697e4 [file] [log] [blame]
Adrià Vilanova Martínez9c418ab2024-12-05 15:34:40 +01001import { InterceptorHandlerPort } from '../interceptors/InterceptorHandler.port';
2import MessageIdTracker from '../MessageIdTracker';
3import { ResponseModifierPort } from '../ResponseModifier.port';
4import FetchProxyCallHandler from './FetchProxyCallHandler';
5
6/**
7 * Class which lets us override window.fetch to proxy the requests through our
8 * internal interceptors to read/modify requests/responses.
9 */
10export default class FetchProxy {
11 private originalFetch: typeof window.fetch;
12 private isInterceptEnabled = false;
13
14 constructor(
15 private responseModifier: ResponseModifierPort,
16 private interceptorHandler: InterceptorHandlerPort,
17 private messageIdTracker: MessageIdTracker,
18 ) {}
19
20 enableInterception() {
21 if (this.isInterceptEnabled) return;
22
23 this.isInterceptEnabled = true;
24
25 this.originalFetch = window.fetch;
26 this.overrideFetch();
27 }
28
29 private overrideFetch() {
30 window.fetch = async (...args) => {
31 const fetchProxyCallhandler = new FetchProxyCallHandler(
32 this.responseModifier,
33 this.interceptorHandler,
34 this.messageIdTracker,
35 this.originalFetch,
36 );
37 return await fetchProxyCallhandler.proxiedFetch(...args);
38 };
39 }
40}