forked from InsurNiffy/niff-Stellar-shurance
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipfs-upload.ts
More file actions
83 lines (71 loc) · 2.3 KB
/
Copy pathipfs-upload.ts
File metadata and controls
83 lines (71 loc) · 2.3 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { IpfsUploadResponse } from '../types/claim';
import { getConfig } from '@/config/env';
export interface UploadProgress {
loaded: number;
total: number;
percentage: number;
}
export type ProgressCallback = (progress: UploadProgress) => void;
const { apiUrl: API_BASE_URL } = getConfig();
/**
* Uploads a file to IPFS via the backend with progress tracking and retry logic.
*/
export async function uploadFileWithProgress(
file: File,
onProgress?: ProgressCallback,
abortSignal?: AbortSignal,
maxRetries = 3
): Promise<IpfsUploadResponse> {
let attempt = 0;
while (attempt < maxRetries) {
try {
return await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', file);
xhr.open('POST', `${API_BASE_URL}/api/ipfs/upload`);
// Handle progress
xhr.upload.onprogress = (event) => {
if (event.lengthComputable && onProgress) {
onProgress({
loaded: event.loaded,
total: event.total,
percentage: Math.round((event.loaded / event.total) * 100),
});
}
};
// Handle completion
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
try {
const response = JSON.parse(xhr.responseText);
resolve(response);
} catch (e) {
reject(new Error('Failed to parse upload response'));
}
} else {
reject(new Error(`Upload failed with status ${xhr.status}`));
}
};
// Handle errors
xhr.onerror = () => reject(new Error('Network error during upload'));
// Handle cancellation
if (abortSignal) {
abortSignal.addEventListener('abort', () => {
xhr.abort();
reject(new Error('Upload aborted'));
});
}
xhr.send(formData);
});
} catch (error) {
attempt++;
if (attempt >= maxRetries || (error instanceof Error && error.message === 'Upload aborted')) {
throw error;
}
// Wait before retry
await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
}
}
throw new Error('Upload failed after maximum retries');
}