Skip to content

Commit

Permalink
fix: clone Response before logging (#1662)
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito authored Jul 20, 2023
1 parent 9c53bd2 commit daa04af
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 29 deletions.
5 changes: 3 additions & 2 deletions src/setupWorker/start/createRequestListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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,
)
})
Expand Down
2 changes: 1 addition & 1 deletion src/utils/logging/serializeResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
}
}
29 changes: 3 additions & 26 deletions src/utils/request/createResponseFromIsomorphicResponse.ts
Original file line number Diff line number Diff line change
@@ -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,
}
})
}

0 comments on commit daa04af

Please sign in to comment.