From 89f99f9c84950da532f620daac26bb246d8f3a0b Mon Sep 17 00:00:00 2001 From: Lenz Weber-Tronic Date: Tue, 12 Sep 2023 14:37:50 +0200 Subject: [PATCH] read json and body text concurrently --- src/link/http/__tests__/HttpLink.ts | 6 ++---- src/link/http/parseAndCheckHttpResponse.ts | 18 ++++++++++++------ 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/link/http/__tests__/HttpLink.ts b/src/link/http/__tests__/HttpLink.ts index 6c9c9f191c4..5346221dc5a 100644 --- a/src/link/http/__tests__/HttpLink.ts +++ b/src/link/http/__tests__/HttpLink.ts @@ -1320,8 +1320,7 @@ describe("HttpLink", () => { makeCallback(resolve, reject, (e: ServerError) => { expect(e.message).toMatch(/Received status code 302/); expect(e.statusCode).toBe(302); - // JSON.parse consumed the buffer, we cannot read it with `.text` anymore - expect(e.result).toEqual(undefined); + expect(e.result).toEqual("Error! Foo bar"); }) ); } @@ -1590,8 +1589,7 @@ describe("HttpLink", () => { expect(e.message).toMatch(/JSON/); expect(e.statusCode).toBe(200); expect(e.response).toBeDefined(); - // bodyText cannot be read a second time - the buffer has been consumed by `Response.json()` - expect(e.bodyText).toBe(""); + expect(e.bodyText).toBe("{"); }) ); } diff --git a/src/link/http/parseAndCheckHttpResponse.ts b/src/link/http/parseAndCheckHttpResponse.ts index b40323cb0cc..03df2a50454 100644 --- a/src/link/http/parseAndCheckHttpResponse.ts +++ b/src/link/http/parseAndCheckHttpResponse.ts @@ -133,8 +133,17 @@ export async function parseJsonBody( response: Response, bodyText?: string ): Promise { - const tryParseAsync = () => - bodyText !== undefined ? JSON.parse(bodyText) : response.json(); + const tryParseAsync = () => { + if (bodyText !== undefined) return JSON.parse(bodyText); + + const json = response.clone().json(); + return response + .text() + .then((text) => { + bodyText = text; + }) + .then(() => json); + }; if (response.status >= 300) { // Network error throwServerError( @@ -151,10 +160,7 @@ export async function parseJsonBody( parseError.name = "ServerParseError"; parseError.response = response; parseError.statusCode = response.status; - parseError.bodyText = - bodyText || - // at this point, the response has already been consumed, so we cannot get the body anymore - ""; + parseError.bodyText = bodyText!; throw parseError; } }