From fe4c0aa983eee9183cd4bd3c930b8609f8239d23 Mon Sep 17 00:00:00 2001 From: Yefis <39944043+SofianD@users.noreply.github.com> Date: Wed, 24 Jan 2024 19:47:52 +0100 Subject: [PATCH] refactor(utils.ts): use undici's method to parse the response body into text (#221) --- src/utils.ts | 12 +++--------- test/utils.spec.ts | 18 +++++++++++++++--- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 5e1234f..9aa0be4 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -41,20 +41,14 @@ export function getEncodingCharset(charset = kDefaultEncodingCharset): BufferEnc * If the response as a content type equal to 'application/json' we automatically parse it with JSON.parse(). */ export async function parseUndiciResponse(response: Dispatcher.ResponseData): Promise { + const body = await response.body.text(); const contentTypeHeader = response.headers["content-type"] as string | undefined; - const { type, parameters } = contentType.parse( + const { type } = contentType.parse( contentTypeHeader ?? kDefaultMimeType ); - response.body.setEncoding(getEncodingCharset(parameters.charset)); - - // Reading the Node.js Stream with the AsyncIterable interface. - let body = ""; - for await (const data of response.body) { - body += data; - } try { - return type === "application/json" ? JSON.parse(body) : body; + return type === "application/json" && body ? JSON.parse(body) : body; } catch (error) { // Note: Even in case of an error we want to be able to recover the body that caused the JSON parsing error. diff --git a/test/utils.spec.ts b/test/utils.spec.ts index d30e961..db818ae 100644 --- a/test/utils.spec.ts +++ b/test/utils.spec.ts @@ -164,7 +164,11 @@ describe("parseUndiciResponse", () => { it("should parse a JSON response with no errors", async() => { const payload = JSON.stringify({ foo: "bar" }); - const body = stream.Readable.from(payload) as any; + const body: any = { + text() { + return Promise.resolve(payload); + } + }; const data = await Utils.parseUndiciResponse<{ foo: string }>({ ...defaultUndiciResponseMeta, body, @@ -180,7 +184,11 @@ describe("parseUndiciResponse", () => { expect.assertions(1); const payload = "{\"foo\": bar}"; - const body = stream.Readable.from(payload) as any; + const body: any = { + text() { + return Promise.resolve(payload); + } + }; try { await Utils.parseUndiciResponse<{ foo: string }>({ @@ -197,7 +205,11 @@ describe("parseUndiciResponse", () => { it("should parse the response as a plain/text", async() => { const payload = "hello world!"; - const body = stream.Readable.from(payload) as any; + const body: any = { + text() { + return Promise.resolve(payload); + } + }; const data = await Utils.parseUndiciResponse({ ...defaultUndiciResponseMeta, body, headers: {}