File size: 1,981 Bytes
efedc31 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | import { useEffect } from "react";
import { useHistoryStore, type HistoryItem } from "../store/useAppStore";
import { API_BASE } from "../api/client";
export async function saveSessionToBackend(
userId: string,
item: HistoryItem,
): Promise<void> {
try {
await fetch(`${API_BASE}/api/sessions/${userId}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(item),
});
} catch {
// fallback silencioso — localStorage es la fuente de verdad local
}
}
export async function deleteSessionFromBackend(
userId: string,
filename: string,
): Promise<void> {
try {
await fetch(
`${API_BASE}/api/sessions/${userId}/${encodeURIComponent(filename)}`,
{ method: "DELETE" },
);
} catch {
// fallback silencioso
}
}
export function useLoadSessionHistory(): void {
const userId = useHistoryStore((s) => s.userId);
const localHistory = useHistoryStore((s) => s.sessionHistory);
const setSessionHistory = useHistoryStore((s) => s.setSessionHistory);
useEffect(() => {
async function load() {
try {
const res = await fetch(`${API_BASE}/api/sessions/${userId}`);
if (!res.ok) return;
const data = await res.json();
const remote: HistoryItem[] = data.items ?? [];
if (remote.length === 0) return;
// Merge remoto + local: dedupe por filename, más reciente gana
const merged = [...remote, ...localHistory];
const seen = new Set<string>();
const deduped = merged.filter((item) => {
if (seen.has(item.filename)) return false;
seen.add(item.filename);
return true;
});
deduped.sort((a, b) => b.uploadedAt - a.uploadedAt);
setSessionHistory(deduped.slice(0, 10));
} catch {
// red no disponible — se mantiene historial local
}
}
load();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [userId]);
}
|