Files
Genarrative/src/editor/shared/jsonClient.ts
kdletters cbc27bad4a
Some checks failed
CI / verify (push) Has been cancelled
init with react+axum+spacetimedb
2026-04-26 18:06:23 +08:00

49 lines
1.2 KiB
TypeScript

import {
API_RESPONSE_ENVELOPE_HEADER,
API_RESPONSE_ENVELOPE_VERSION,
parseApiErrorMessage,
unwrapApiResponse,
} from '../../../packages/shared/src/http';
export async function fetchJson<T>(
url: string,
fallbackMessage = '请求失败',
): Promise<T> {
const response = await fetch(url, {
headers: {
[API_RESPONSE_ENVELOPE_HEADER]: API_RESPONSE_ENVELOPE_VERSION,
},
});
const responseText = await response.text();
if (!response.ok) {
throw new Error(parseApiErrorMessage(responseText, `${fallbackMessage}: ${response.status}`));
}
return responseText
? unwrapApiResponse<T>(JSON.parse(responseText) as T)
: ({} as T);
}
export async function saveJsonObject(
url: string,
payload: Record<string, unknown>,
fallbackMessage = '保存失败',
) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
[API_RESPONSE_ENVELOPE_HEADER]: API_RESPONSE_ENVELOPE_VERSION,
},
body: JSON.stringify(payload, null, 2),
});
const responseText = await response.text();
if (!response.ok) {
throw new Error(parseApiErrorMessage(responseText, fallbackMessage));
}
}
export { parseApiErrorMessage };