From 37de1ed2006a2408e3c5f47a131770243f7a331a Mon Sep 17 00:00:00 2001 From: Artem Zakharchenko Date: Fri, 15 Nov 2024 12:30:36 +0100 Subject: [PATCH] fix(fetch): ensure response url --- src/interceptors/fetch/index.ts | 7 +++---- src/utils/fetchUtils.ts | 26 ++++++++++++++++++-------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/src/interceptors/fetch/index.ts b/src/interceptors/fetch/index.ts index 4c82d0f9..d134fc16 100644 --- a/src/interceptors/fetch/index.ts +++ b/src/interceptors/fetch/index.ts @@ -75,10 +75,9 @@ export class FetchInterceptor extends Interceptor { const response = decompressedStream === null ? rawResponse - : new FetchResponse(decompressedStream, { - ...rawResponse, - url: request.url, - }) + : new FetchResponse(decompressedStream, rawResponse) + + FetchResponse.setUrl(request.url, response) /** * Undici's handling of following redirect responses. diff --git a/src/utils/fetchUtils.ts b/src/utils/fetchUtils.ts index cc58bf2b..1c5d2377 100644 --- a/src/utils/fetchUtils.ts +++ b/src/utils/fetchUtils.ts @@ -27,6 +27,23 @@ export class FetchResponse extends Response { return !FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(status) } + static setUrl(url: string | undefined, response: Response): void { + if (!url) { + return + } + + if (response.url != null) { + return + } + + Object.defineProperty(response, 'url', { + value: url, + enumerable: true, + configurable: true, + writable: false, + }) + } + constructor(body?: BodyInit | null, init: FetchResponseInit = {}) { const status = init.status ?? 200 const safeStatus = FetchResponse.isConfigurableStatusCode(status) @@ -60,13 +77,6 @@ export class FetchResponse extends Response { } } - if (init.url) { - Object.defineProperty(this, 'url', { - value: init.url, - enumerable: true, - configurable: true, - writable: false, - }) - } + FetchResponse.setUrl(init.url, this) } }