From daa04af4075b06607b81ed23bbe5ea09d56e8825 Mon Sep 17 00:00:00 2001 From: Artem Zakharchenko Date: Thu, 20 Jul 2023 12:17:45 +0200 Subject: [PATCH] fix: clone Response before logging (#1662) --- .../start/createRequestListener.ts | 5 ++-- src/utils/logging/serializeResponse.ts | 2 +- .../createResponseFromIsomorphicResponse.ts | 29 ++----------------- 3 files changed, 7 insertions(+), 29 deletions(-) diff --git a/src/setupWorker/start/createRequestListener.ts b/src/setupWorker/start/createRequestListener.ts index 1b4cfa184..090b13c46 100644 --- a/src/setupWorker/start/createRequestListener.ts +++ b/src/setupWorker/start/createRequestListener.ts @@ -54,6 +54,7 @@ export const createRequestListener = ( } const responseInstance = new Response(response.body, response) + const responseForLogs = responseInstance.clone() const responseBodyBuffer = await responseInstance.arrayBuffer() // If the mocked response has no body, keep it that way. @@ -73,10 +74,10 @@ export const createRequestListener = ( ) if (!options.quiet) { - context.emitter.once('response:mocked', async (response) => { + context.emitter.once('response:mocked', async () => { handler.log( publicRequest, - await serializeResponse(response), + await serializeResponse(responseForLogs), parsedRequest, ) }) diff --git a/src/utils/logging/serializeResponse.ts b/src/utils/logging/serializeResponse.ts index 24230d1db..c46303d75 100644 --- a/src/utils/logging/serializeResponse.ts +++ b/src/utils/logging/serializeResponse.ts @@ -11,6 +11,6 @@ export async function serializeResponse( // Serialize the response body to a string // so it's easier to process further down the chain in "prepareResponse" (browser-only) // and "parseBody" (ambiguous). - body: await response.text(), + body: await response.clone().text(), } } diff --git a/src/utils/request/createResponseFromIsomorphicResponse.ts b/src/utils/request/createResponseFromIsomorphicResponse.ts index f314e8e15..759d5cd26 100644 --- a/src/utils/request/createResponseFromIsomorphicResponse.ts +++ b/src/utils/request/createResponseFromIsomorphicResponse.ts @@ -1,34 +1,11 @@ -import { encodeBuffer, IsomorphicResponse } from '@mswjs/interceptors' - -const noop = () => { - throw new Error('Not implemented') -} +import { IsomorphicResponse } from '@mswjs/interceptors' export function createResponseFromIsomorphicResponse( response: IsomorphicResponse, ): Response { - return { - ...response, - ok: response.status >= 200 && response.status < 300, - url: '', - type: 'default', + return new Response(response.body, { status: response.status, statusText: response.statusText, headers: response.headers, - body: new ReadableStream(), - redirected: response.headers.get('Location') != null, - async text() { - return response.body || '' - }, - async json() { - return JSON.parse(response.body || '') - }, - async arrayBuffer() { - return encodeBuffer(response.body || '') - }, - bodyUsed: false, - formData: noop, - blob: noop, - clone: noop, - } + }) }