49 lines
1.2 KiB
TypeScript
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 };
|