refactor(hooks): introduce unified post-change sync utility

- Add postChangeSync.ts utility with Result pattern for graceful error handling
- Replace try-catch with syncCurrentProvidersLiveSafe in useImportExport
- Add directory-change-triggered sync in useSettings to maintain SSOT
- Introduce partial-success status to distinguish import success from sync failures
- Add test coverage for sync behavior in different scenarios

This refactoring ensures config.json changes are reliably synced to live
files while providing better user feedback for edge cases.
This commit is contained in:
Jason
2025-11-01 23:58:29 +08:00
parent 87f408c163
commit 2ebe34810c
4 changed files with 52 additions and 4 deletions

View File

@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { settingsApi } from "@/lib/api";
import { syncCurrentProvidersLiveSafe } from "@/utils/postChangeSync";
export type ImportStatus =
| "idle"
@@ -105,8 +106,8 @@ export function useImportExport(
setBackupId(result.backupId ?? null);
try {
await settingsApi.syncCurrentProvidersLive();
const syncResult = await syncCurrentProvidersLiveSafe();
if (syncResult.ok) {
setStatus("success");
toast.success(
t("settings.importSuccess", {
@@ -117,8 +118,11 @@ export function useImportExport(
successTimerRef.current = window.setTimeout(() => {
void onImportSuccess?.();
}, 1500);
} catch (error) {
console.error("[useImportExport] Failed to sync live config", error);
} else {
console.error(
"[useImportExport] Failed to sync live config",
syncResult.error,
);
setStatus("partial-success");
toast.warning(
t("settings.importPartialSuccess", {