From 2b42fa0206258762b545208f706265a195d457f5 Mon Sep 17 00:00:00 2001 From: Usame Algan Date: Wed, 28 Feb 2024 11:27:34 +0100 Subject: [PATCH 1/2] fix: Don't throw for 204 responses --- src/utils.ts | 2 +- tests/utils.test.ts | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/utils.ts b/src/utils.ts index 111029e2..af4837bf 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -41,7 +41,7 @@ async function parseResponse(resp: Response): Promise { let json try { - json = await resp.json() + json = resp.status === 204 ? {} : await resp.json() } catch { if (resp.headers && resp.headers.get('content-length') !== '0') { throw new Error(`Invalid response content: ${resp.statusText}`) diff --git a/tests/utils.test.ts b/tests/utils.test.ts index 81488689..9984db35 100644 --- a/tests/utils.test.ts +++ b/tests/utils.test.ts @@ -197,5 +197,26 @@ describe('utils', () => { }, }) }) + + it('should not throw for a 204 response', async () => { + const jsonMock = jest.fn() + fetchMock.mockImplementation(() => { + return Promise.resolve({ + ok: true, + status: 204, + json: jsonMock, + }) + }) + + await expect(fetchData('/test/safe', 'DELETE')).resolves.toEqual({}) + expect(jsonMock).not.toHaveBeenCalled() + + expect(fetch).toHaveBeenCalledWith('/test/safe', { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json', + }, + }) + }) }) }) From 53d9e76169e177053a79cd7caf895a9042a95f86 Mon Sep 17 00:00:00 2001 From: Usame Algan Date: Wed, 28 Feb 2024 15:25:06 +0100 Subject: [PATCH 2/2] chore: Add comment for 204 status --- src/utils.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/utils.ts b/src/utils.ts index af4837bf..6c4696b6 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -41,6 +41,7 @@ async function parseResponse(resp: Response): Promise { let json try { + // An HTTP 204 - No Content response doesn't contain a body so trying to call .json() on it would throw json = resp.status === 204 ? {} : await resp.json() } catch { if (resp.headers && resp.headers.get('content-length') !== '0') {