This commit is contained in:
48
src/editor/shared/jsonClient.ts
Normal file
48
src/editor/shared/jsonClient.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
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 };
|
||||
Reference in New Issue
Block a user