Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: only fallback to text on error #14

Merged
merged 2 commits into from
Jan 29, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fix: only fallback to text on error
JounQin committed Jan 29, 2024
commit 1b9b34dd0b29c19acb818eec78d6e36ebb050498
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -97,7 +97,7 @@ export const createFetchApi = (fetch = globalThis.fetch) => {
return response
}
throw Object.assign(new Error(response.statusText), {
data: extractDataFromResponse(response, type),
data: extractDataFromResponse(response, type, true),
response,
})
}
28 changes: 23 additions & 5 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -60,31 +60,38 @@ export const normalizeUrl = (url: string, query?: URLSearchParamsOptions) => {
export async function extractDataFromResponse(
res: Response,
type: null,
fallback?: boolean,
): Promise<Response>
export async function extractDataFromResponse(
res: Response,
type: 'arrayBuffer',
fallback?: boolean,
): Promise<ArrayBuffer>
export async function extractDataFromResponse(
res: Response,
type: 'blob',
fallback?: boolean,
): Promise<Blob>
export async function extractDataFromResponse<T>(
res: Response,
type: 'json',
fallback?: boolean,
): Promise<T>
export async function extractDataFromResponse(
res: Response,
type: 'text',
fallback?: boolean,
): Promise<string>
export async function extractDataFromResponse(
res: Response,
type: ResponseType,
fallback?: boolean,
): Promise<unknown>
// eslint-disable-next-line sonarjs/cognitive-complexity
export async function extractDataFromResponse(
res: Response,
type: ResponseType,
fallback?: boolean,
) {
let data: unknown
if (type != null) {
@@ -93,15 +100,26 @@ export async function extractDataFromResponse(
// data could be empty text
data = await res.clone().text()
} catch {}
if (type === 'json' && (data = (data as string).trim())) {
try {
data = JSON.parse(data as string)
} catch {}
if (type === 'json') {
if ((data = (data as string).trim())) {
try {
data = JSON.parse(data as string)
} catch (err) {
if (!fallback) {
throw err
}
}
} else {
data = null
}
}
} else {
try {
data = await res.clone()[type]()
} catch {
} catch (err) {
if (!fallback) {
throw err
}
data = await res.clone().text()
}
}