From b8009c043fb0752b11c85892287c2cc3be69a31a Mon Sep 17 00:00:00 2001 From: Guillaume NICOLAS Date: Mon, 9 Oct 2023 11:56:05 +0200 Subject: [PATCH] have to clone response to be able to parse body in interceptors --- packages/http/src/http.common.test.ts | 11 ++++++++++- packages/http/src/http.common.ts | 7 ++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/http/src/http.common.test.ts b/packages/http/src/http.common.test.ts index 3ec38d9ed78..f4baf5071c6 100644 --- a/packages/http/src/http.common.test.ts +++ b/packages/http/src/http.common.test.ts @@ -54,7 +54,10 @@ describe('handleBody', () => { const blob = jest.fn(() => Promise.resolve()); - await handleBody({ blob, headers } as any); + await handleBody({ + headers, + clone: jest.fn().mockReturnValue({ blob }), + } as any); expect(blob).toHaveBeenCalled(); }); @@ -77,6 +80,12 @@ describe('handleBody', () => { expect(result.data).toBe(''); }); + it("should manage response's body and return a clone with unused body", async () => { + const result = await handleBody(new Response('ok') as any); + expect(result.data).toBe('ok'); + expect(result.response.bodyUsed).toBe(false); + }); + describe('#handleHttpResponse', () => { it('should handle the response with 2xx code', async () => { const headers = new Headers(); diff --git a/packages/http/src/http.common.ts b/packages/http/src/http.common.ts index 3d79d193b7f..ee6b27e2216 100644 --- a/packages/http/src/http.common.ts +++ b/packages/http/src/http.common.ts @@ -40,17 +40,18 @@ export function encodePayload(headers: HeadersInit, payload: any) { * @return {Promise} A promise that resolves with the result of parsing the body */ export async function handleBody(response: Response) { + const clonedResponse = response.clone(); const { headers } = response; const contentType = headers.get('Content-Type'); if (contentType && contentType.includes('application/json')) { - return response.json().then(data => ({ data, response })); + return clonedResponse.json().then(data => ({ data, response })); } if (contentType && contentType.includes('application/zip')) { - return response.blob().then(data => ({ data, response })); + return clonedResponse.blob().then(data => ({ data, response })); } - return response.text().then(data => ({ data, response })); + return clonedResponse.text().then(data => ({ data, response })); } /**