uploadv2 / services /hfService.ts
Twan07's picture
Create services/hfService.ts
67a39f2 verified
raw
history blame
1.82 kB
/**
* FRONTEND SERVICE
*
* This service no longer uses @huggingface/hub directly.
* It sends files to our local Node.js backend (server.js).
*/
// Use relative URL so Vite proxy can forward it to localhost:3001
const BACKEND_URL = '/api/upload';
interface UploadPayload {
file: File;
path: string;
}
/**
* Uploads a file by sending it to the Node.js backend.
*
* @param payload File and destination path
* @returns The public URL of the uploaded file
*/
export const uploadFileToHub = async (payload: UploadPayload): Promise<string> => {
const { file, path } = payload;
const formData = new FormData();
// Append text fields BEFORE files is good practice for some parsers
formData.append('path', path);
formData.append('file', 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.url;
} catch (err: any) {
console.error("[FE] API Call Failed:", err);
const errorMessage = err?.message || "Unknown error";
// Suggest running the server if connection fails
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('backend running')) {
throw new Error("Cannot connect to Backend. Make sure to run 'npm run server' in a separate terminal.");
}
throw new Error(errorMessage);
}
};