Skip to content

Commit

Permalink
fix(serializeResponse): read response as text
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Jun 8, 2023
1 parent 4cf3e63 commit 169311e
Show file tree
Hide file tree
Showing 5 changed files with 18 additions and 60 deletions.
4 changes: 2 additions & 2 deletions src/setupWorker/start/createFallbackRequestListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ export function createFallbackRequestListener(
},
onMockedResponse(_, { handler, publicRequest, parsedRequest }) {
if (!options.quiet) {
context.emitter.once('response:mocked', (response) => {
context.emitter.once('response:mocked', async (response) => {
handler.log(
publicRequest,
serializeResponse(response),
await serializeResponse(response),
parsedRequest,
)
})
Expand Down
4 changes: 2 additions & 2 deletions src/setupWorker/start/createRequestListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@ export const createRequestListener = (
)

if (!options.quiet) {
context.emitter.once('response:mocked', (response) => {
context.emitter.once('response:mocked', async (response) => {
handler.log(
publicRequest,
serializeResponse(response),
await serializeResponse(response),
parsedRequest,
)
})
Expand Down
38 changes: 2 additions & 36 deletions src/utils/logging/prepareResponse.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { prepareResponse } from './prepareResponse'

test('parses a JSON response body given a "Content-Type:*/json" header', () => {
const res = prepareResponse({
test('parses a JSON response body given a "Content-Type:*/json" header', async () => {
const res = await prepareResponse({
status: 200,
statusText: 'OK',
headers: {
Expand Down Expand Up @@ -50,37 +50,3 @@ test('returns a non-JSON response body as-is', () => {
// Returns a non-JSON response body as-is
expect(res.body).toEqual('text-body')
})

test('parse the json of a readableStream', async () => {
const res = prepareResponse({
status: 200,
statusText: 'OK',
headers: {
'Content-Type': 'application/json',
},
body: new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(`{"property":2}`))
controller.close()
},
}),
})

expect(await res.body).toEqual({ property: 2 })
})

test('return the text of a readableStream', async () => {
const res = prepareResponse({
status: 200,
statusText: 'OK',
headers: {},
body: new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(`{"property":2}`))
controller.close()
},
}),
})

expect(await res.body).toEqual(`{"property":2}`)
})
17 changes: 2 additions & 15 deletions src/utils/logging/prepareResponse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,11 @@ import { parseBody } from '../request/parseBody'
/**
* Formats a mocked response for introspection in the browser's console.
*/
export function prepareResponse(res: SerializedResponse<any>) {
export function prepareResponse(res: SerializedResponse<string>) {
const responseHeaders = objectToHeaders(res.headers)

// Parse a response JSON body for preview in the logs
let parsedBody: ReturnType<typeof parseBody> | Promise<any> = parseBody(
res.body,
responseHeaders,
)

if (parsedBody instanceof ReadableStream) {
const response = new Response(parsedBody, { headers: responseHeaders })

const hasJsonContent = (
responseHeaders?.get('content-type')?.toLowerCase() || ''
).includes('json')

parsedBody = hasJsonContent ? response.json() : response.text()
}
const parsedBody = parseBody(res.body, responseHeaders)

return {
...res,
Expand Down
15 changes: 10 additions & 5 deletions src/utils/logging/serializeResponse.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { flattenHeadersObject, headersToObject } from 'headers-polyfill'
import type { SerializedResponse } from '../../setupWorker/glossary'

export function serializeResponse(source: Response): SerializedResponse<any> {
export async function serializeResponse(
response: Response,
): Promise<SerializedResponse<string>> {
return {
status: source.status,
statusText: source.statusText,
headers: flattenHeadersObject(headersToObject(source.headers)),
body: source.body,
status: response.status,
statusText: response.statusText,
headers: flattenHeadersObject(headersToObject(response.headers)),
// 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(),
}
}

0 comments on commit 169311e

Please sign in to comment.