Skip to content

Commit

Permalink
fix(fetch): avoid relying on .blob()
Browse files Browse the repository at this point in the history
  • Loading branch information
matthieusieben committed Apr 12, 2024
1 parent a1bd979 commit 838f739
Showing 1 changed file with 35 additions and 48 deletions.
83 changes: 35 additions & 48 deletions packages/fetch/src/fetch-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,22 @@ import { Json, ifObject, ifString } from './util.js'
import { TransformedResponse } from './transformed-response.js'

export type ResponseTranformer = Transformer<Response>
export type ResponseMessageGetter = Transformer<Response, string | undefined>

async function extractResponseMessage(
headers: Headers,
body?: Blob | null,
): Promise<string | undefined> {
if (!body) return undefined
const extractResponseMessage: ResponseMessageGetter = async (response) => {
if (!response.body) return undefined

const contentType = headers.get('content-type')
const contentType = response.headers.get('content-type')
if (!contentType) return undefined

const mimeType = contentType.split(';')[0].trim()
if (!mimeType) return undefined

try {
if (mimeType === 'text/plain') {
return await body.text()
return await response.text()
} else if (/^application\/(?:[^+]+\+)?json$/i.test(mimeType)) {
const json = await body.text().then(JSON.parse)
const json = await response.json()

if (typeof json === 'string') return json

Expand All @@ -47,43 +45,44 @@ export class FetchResponseError extends FetchError {
constructor(
statusCode: number,
message?: string,
readonly body?: Blob | null,
options?: FetchErrorOptions,
) {
super(statusCode, message, options)
}

static async from(
response: Response,
status = response.status,
customMessage?: string,
options?: FetchErrorOptions,
customMessage: string | ResponseMessageGetter = extractResponseMessage,
options?: Omit<FetchErrorOptions, 'response'>,
) {
// Make sure the body gets consumed as, in some environments (Node 👀), the
// response will not be GC'd.
const body = response.body
? !response.bodyUsed
? await response.blob()
: undefined
: null

const message =
customMessage ??
(await extractResponseMessage(response.headers, body)) ??
response.statusText
typeof customMessage === 'string'
? customMessage
: typeof customMessage === 'function'
? await customMessage(response)
: undefined

return new FetchResponseError(status, message, body, {
...options,
response,
})
// Make sure the body gets consumed as, in some environments (Node 👀), the
// response will not automatically be GC'd.
await response.body?.cancel()

return new FetchResponseError(
response.status,
message ?? response.statusText,
{
...options,
response,
},
)
}
}

export function fetchOkProcessor(): ResponseTranformer {
export function fetchOkProcessor(
customMessage?: string | ResponseMessageGetter,
): ResponseTranformer {
return async (response) => {
if (response.ok) return response

throw await FetchResponseError.from(response)
throw await FetchResponseError.from(response, customMessage)
}
}

Expand All @@ -106,7 +105,7 @@ export async function fetchResponseMaxSize(
if (contentLength) {
const length = Number(contentLength)
if (!(length < maxBytes)) {
const err = new FetchResponseError(502, 'Response too large', undefined, {
const err = new FetchResponseError(502, 'Response too large', {
response,
})
await response.body.cancel(err)
Expand All @@ -125,9 +124,7 @@ export async function fetchResponseMaxSize(
ctrl.enqueue(chunk)
} else {
ctrl.error(
new FetchResponseError(502, 'Response too large', undefined, {
response,
}),
new FetchResponseError(502, 'Response too large', { response }),
)
}
},
Expand Down Expand Up @@ -185,32 +182,22 @@ export async function jsonTranformer<T = Json>(
response: Response,
): Promise<ParsedJsonResponse<T>> {
if (response.body === null) {
throw new FetchResponseError(502, 'No response body', null, {
throw new FetchResponseError(502, 'No response body', {
response,
})
}

if (response.bodyUsed) {
throw new FetchResponseError(502, 'Response body already used', undefined, {
throw new FetchResponseError(502, 'Response body already used', {
response,
})
}

// Read as blob to allow throwing with the body in case on invalid JSON (for debugging/logging purposes mainly)
const body = await response.blob().catch(async (cause) => {
throw new FetchResponseError(
502,
'Failed to read response body',
undefined,
{ response, cause },
)
})

try {
const json = (await body.text().then(JSON.parse)) as T
const json = (await response.json()) as T
return { response, json }
} catch (cause) {
throw new FetchResponseError(502, 'Unable to parse response JSON', body, {
throw new FetchResponseError(502, 'Unable to parse response as JSON', {
response,
cause,
})
Expand Down

0 comments on commit 838f739

Please sign in to comment.