Twan07 commited on
Commit
67a39f2
·
verified ·
1 Parent(s): b49e394

Create services/hfService.ts

Browse files
Files changed (1) hide show
  1. services/hfService.ts +59 -0
services/hfService.ts ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * FRONTEND SERVICE
3
+ *
4
+ * This service no longer uses @huggingface/hub directly.
5
+ * It sends files to our local Node.js backend (server.js).
6
+ */
7
+
8
+ // Use relative URL so Vite proxy can forward it to localhost:3001
9
+ const BACKEND_URL = '/api/upload';
10
+
11
+ interface UploadPayload {
12
+ file: File;
13
+ path: string;
14
+ }
15
+
16
+ /**
17
+ * Uploads a file by sending it to the Node.js backend.
18
+ *
19
+ * @param payload File and destination path
20
+ * @returns The public URL of the uploaded file
21
+ */
22
+ export const uploadFileToHub = async (payload: UploadPayload): Promise<string> => {
23
+ const { file, path } = payload;
24
+
25
+ const formData = new FormData();
26
+ // Append text fields BEFORE files is good practice for some parsers
27
+ formData.append('path', path);
28
+ formData.append('file', file);
29
+
30
+ try {
31
+ const response = await fetch(BACKEND_URL, {
32
+ method: 'POST',
33
+ body: formData,
34
+ });
35
+
36
+ // Handle non-JSON responses (like 404 or 502 from proxy)
37
+ const contentType = response.headers.get("content-type");
38
+ if (!contentType || !contentType.includes("application/json")) {
39
+ throw new Error(`Server returned unexpected ${response.status} ${response.statusText}. Is the backend running?`);
40
+ }
41
+
42
+ const data = await response.json();
43
+
44
+ if (!response.ok || !data.success) {
45
+ throw new Error(data.error || 'Upload failed on server');
46
+ }
47
+
48
+ return data.url;
49
+
50
+ } catch (err: any) {
51
+ console.error("[FE] API Call Failed:", err);
52
+ const errorMessage = err?.message || "Unknown error";
53
+ // Suggest running the server if connection fails
54
+ if (errorMessage.includes('Failed to fetch') || errorMessage.includes('backend running')) {
55
+ throw new Error("Cannot connect to Backend. Make sure to run 'npm run server' in a separate terminal.");
56
+ }
57
+ throw new Error(errorMessage);
58
+ }
59
+ };