/** * FRONTEND SERVICE * * This service communicates with the Node.js backend (server.js). * It supports Batch Uploading to maximize speed. */ // Use relative URL so Vite proxy can forward it to localhost:3001 const BACKEND_URL = '/api/upload'; interface BatchItem { id: string; // Used for tracking file: File; path: string; } /** * Uploads multiple files in a single request. * * @param items Array of files and their destination paths * @returns Array of public URLs for the uploaded files */ export const uploadBatchToHub = async (items: BatchItem[]): Promise => { const formData = new FormData(); // Append all files and paths to FormData // Multer on the backend will receive these as arrays items.forEach(item => { formData.append('paths', item.path); formData.append('files', item.file); }); try { const response = await fetch(BACKEND_URL, { method: 'POST', body: formData, }); // Handle non-JSON responses (like 404 or 502 from proxy) const contentType = response.headers.get("content-type"); if (!contentType || !contentType.includes("application/json")) { throw new Error(`Server returned unexpected ${response.status} ${response.statusText}. Is the backend running?`); } const data = await response.json(); if (!response.ok || !data.success) { throw new Error(data.error || 'Upload failed on server'); } return data.urls; } catch (err: any) { console.error("[FE] Batch Upload Failed:", err); const errorMessage = err?.message || "Unknown error"; if (errorMessage.includes('Failed to fetch') || errorMessage.includes('backend running')) { throw new Error("Cannot connect to Backend. Make sure 'npm run server' is running."); } throw new Error(errorMessage); } };