Adrià Vilanova MartÃnez | 9c418ab | 2024-12-05 15:34:40 +0100 | [diff] [blame^] | 1 | import { InterceptorHandlerPort } from '../interceptors/InterceptorHandler.port'; |
| 2 | import MessageIdTracker from '../MessageIdTracker'; |
| 3 | import { ResponseModifierPort } from '../ResponseModifier.port'; |
| 4 | import 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 | */ |
| 10 | export 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 | } |