fix(data): 增加全局保存失败保护

This commit is contained in:
Script Generator
2026-07-03 19:36:18 +08:00
parent 516a5f1b63
commit b4a3c990b4
17 changed files with 727 additions and 132 deletions

View File

@@ -37,6 +37,12 @@ const serverDataCache = new Map<ServerDataKey, {
}>();
const serverDataLoadPromises = new Map<ServerDataKey, Promise<unknown | null>>();
export const SERVER_DATA_CACHE_MS = 30_000;
export const SERVER_DATA_SAVE_ERROR_EVENT = 'ftb:server-data-save-error';
export type ServerDataSaveErrorDetail = {
key: ServerDataKey;
message: string;
};
type LoadServerDataOptions = {
force?: boolean;
@@ -54,6 +60,24 @@ export class ServerDataConflictError<T = unknown> extends Error {
}
}
function getServerDataSaveErrorMessage(error: unknown) {
if (error instanceof ServerDataConflictError) return '数据已被其他用户更新,请刷新后重试';
if (error instanceof Error && error.message) return error.message;
return '保存失败,请检查网络或 API 服务';
}
function notifyServerDataSaveFailure(key: ServerDataKey, error: unknown) {
if (typeof window === 'undefined') return;
window.dispatchEvent(
new CustomEvent(SERVER_DATA_SAVE_ERROR_EVENT, {
detail: {
key,
message: getServerDataSaveErrorMessage(error),
},
}),
);
}
export async function loadServerData<T>(
key: ServerDataKey,
options: LoadServerDataOptions = {},
@@ -107,12 +131,15 @@ export async function saveServerData<T>(key: ServerDataKey, value: T): Promise<v
error.status === 409 &&
isServerDataConflictBody<T>(error.body, key)
) {
throw new ServerDataConflictError(
const conflict = new ServerDataConflictError(
error.body.key,
error.body.currentValue,
error.body.currentVersion,
);
notifyServerDataSaveFailure(key, conflict);
throw conflict;
}
notifyServerDataSaveFailure(key, error);
throw error;
}
}