feat: 云同步改为实时自动上传 — 收藏/最近使用/网站收藏/生成记录一变化3秒内自动推送云端
This commit is contained in:
1 parent
580c5997b4
commit
827547e622
1 file changed
+64
@@ -88,6 +88,70 @@ function mergeData(server: Record<string, any>, mine: Record<string, any>): Reco
|
||||
return out;
|
||||
}
|
||||
|
||||
// ================= 自动上传:同步键数据一变化就推到云端 =================
|
||||
let autoPending: ReturnType<typeof setTimeout> | undefined;
|
||||
let autoBusy = false;
|
||||
|
||||
function shouldAutoSync(k: string): boolean {
|
||||
return SYNC_KEYS.includes(k) || k.startsWith('gen-history:');
|
||||
}
|
||||
|
||||
/** push-only sync: merge local into server WITHOUT writing back (protects the fresh local value) */
|
||||
async function pushUpOnly() {
|
||||
if (autoBusy) {
|
||||
scheduleAutoSync(); // busy -> retry after
|
||||
return;
|
||||
}
|
||||
autoBusy = true;
|
||||
try {
|
||||
const mine = collectLocal();
|
||||
const { status, body } = await apiFetch('/user/data');
|
||||
if (status !== 200) {
|
||||
return;
|
||||
}
|
||||
const server = body.data?.data ?? {};
|
||||
const merged = mergeData(server, mine);
|
||||
await apiFetch('/user/data', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ data: merged }),
|
||||
});
|
||||
}
|
||||
catch { /* offline etc. */ }
|
||||
finally {
|
||||
autoBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleAutoSync() {
|
||||
if (autoPending) {
|
||||
clearTimeout(autoPending);
|
||||
}
|
||||
autoPending = setTimeout(() => {
|
||||
if (useUserAuth().isLoggedIn.value) {
|
||||
pushUpOnly().catch(() => {});
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// wrap localStorage so any write to a synced key schedules an upload
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
const origSet = localStorage.setItem.bind(localStorage);
|
||||
const origRemove = localStorage.removeItem.bind(localStorage);
|
||||
localStorage.setItem = (k: string, v: string) => {
|
||||
origSet(k, v);
|
||||
if (shouldAutoSync(k)) {
|
||||
scheduleAutoSync();
|
||||
}
|
||||
};
|
||||
localStorage.removeItem = (k: string) => {
|
||||
origRemove(k);
|
||||
if (shouldAutoSync(k)) {
|
||||
scheduleAutoSync();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function useCloudSync() {
|
||||
const { isLoggedIn } = useUserAuth();
|
||||
|
||||
|
||||
Reference in new issue
Block a user