fix(data): 增加全局保存失败保护
This commit is contained in:
28
apps/web/lib/optimistic-persistence.ts
Normal file
28
apps/web/lib/optimistic-persistence.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
type OptimisticRollbackOptions<T> = {
|
||||
save: () => Promise<void>;
|
||||
expected: T;
|
||||
getCurrent: () => T;
|
||||
rollback: () => void;
|
||||
};
|
||||
|
||||
export async function saveWithOptimisticRollback<T>({
|
||||
save,
|
||||
expected,
|
||||
getCurrent,
|
||||
rollback,
|
||||
}: OptimisticRollbackOptions<T>): Promise<void> {
|
||||
try {
|
||||
await save();
|
||||
} catch (error) {
|
||||
if (Object.is(getCurrent(), expected)) {
|
||||
rollback();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function scheduleSaveWithOptimisticRollback<T>(
|
||||
options: OptimisticRollbackOptions<T>,
|
||||
): void {
|
||||
void saveWithOptimisticRollback(options).catch(() => undefined);
|
||||
}
|
||||
Reference in New Issue
Block a user