Skip to content

Commit 4c6437e

Browse files
committed
Update fetch.ts
1 parent ead7ac1 commit 4c6437e

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

src/lib/api/fetch.ts

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,18 @@ const jqHeader = 'X-jq';
1111
const contentTypeHeader = 'Content-Type';
1212

1313
// fetchApiServer is a wrapper around fetch that adds the necessary headers for the Crate API or the MCP API server.
14+
export const parseJsonOrText = async (res: Response): Promise<unknown> => {
15+
try {
16+
return await res.json();
17+
} catch {
18+
try {
19+
return await res.text();
20+
} catch {
21+
return '';
22+
}
23+
}
24+
};
25+
1426
export const fetchApiServer = async (
1527
path: string,
1628
config: ApiConfig,
@@ -53,7 +65,7 @@ export const fetchApiServer = async (
5365
window.location.replace(`/api/auth/onboarding/login?redirectTo=${encodeURIComponent(getRedirectSuffix())}`);
5466
}
5567
const error = new APIError('An error occurred while fetching the data.', res.status);
56-
error.info = await res.json();
68+
error.info = await parseJsonOrText(res);
5769
throw error;
5870
}
5971

@@ -66,10 +78,10 @@ export const fetchApiServerJson = async <T>(
6678
jq?: string,
6779
httpMethod: string = 'GET',
6880
body?: BodyInit,
69-
): Promise<T> => {
81+
): Promise<T | string> => {
7082
const res = await fetchApiServer(path, config, jq, httpMethod, body);
71-
72-
return await res.json();
83+
const data = await parseJsonOrText(res);
84+
return data as T | string;
7385
};
7486

7587
// request is of [path, config, jq]
@@ -79,7 +91,7 @@ export const fetchApiServerJsonMultiple = (requests: [string | null, ApiConfig,
7991
.filter((r) => r[0] !== null)
8092
.map(([path, config, jq]) =>
8193
// @ts-expect-error path is not null
82-
fetchApiServer(path, config, jq).then((res) => res.json()),
94+
fetchApiServer(path, config, jq).then((res) => parseJsonOrText(res)),
8395
),
8496
);
8597
};

0 commit comments

Comments
 (0)