doctor-mail/apps/web/src/hooks/useTusUpload.ts

84 lines
2.1 KiB
TypeScript
Raw Normal View History

2025-01-22 23:19:51 +08:00
import { useState } from "react";
import * as tus from "tus-js-client";
interface UploadResult {
2025-01-25 00:46:59 +08:00
url: string;
fileId: string;
// resource: any;
2025-01-22 23:19:51 +08:00
}
export function useTusUpload() {
const [progress, setProgress] = useState(0);
const [isUploading, setIsUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
2025-01-25 00:46:59 +08:00
const getFileId = (url: string) => {
const parts = url.split("/");
// Find the index of the 'upload' segment
const uploadIndex = parts.findIndex((part) => part === "upload");
if (uploadIndex === -1 || uploadIndex + 4 >= parts.length) {
throw new Error("Invalid upload URL format");
}
// Get the date parts and file ID (4 segments after 'upload')
return parts.slice(uploadIndex + 1, uploadIndex + 5).join("/");
};
const handleFileUpload = async (
2025-01-22 23:19:51 +08:00
file: File,
onSuccess: (result: UploadResult) => void,
onError: (error: Error) => void
) => {
setIsUploading(true);
setProgress(0);
setUploadError(null);
const upload = new tus.Upload(file, {
2025-01-25 00:46:59 +08:00
endpoint: "http://localhost:3000/upload",
2025-01-22 23:19:51 +08:00
retryDelays: [0, 1000, 3000, 5000],
metadata: {
filename: file.name,
filetype: file.type,
},
onProgress: (bytesUploaded, bytesTotal) => {
const uploadProgress = (
(bytesUploaded / bytesTotal) *
100
).toFixed(2);
setProgress(Number(uploadProgress));
},
2025-01-25 00:46:59 +08:00
onSuccess: async () => {
try {
if (upload.url) {
const fileId = getFileId(upload.url);
// const resource = await pollResourceStatus(fileId);
setIsUploading(false);
setProgress(100);
onSuccess({
url: upload.url,
fileId,
// resource,
});
}
} catch (error) {
const err =
error instanceof Error
? error
: new Error("Unknown error");
setIsUploading(false);
setUploadError(err.message);
onError(err);
}
2025-01-22 23:19:51 +08:00
},
onError: (error) => {
setIsUploading(false);
setUploadError(error.message);
onError(error);
},
});
upload.start();
};
return {
progress,
isUploading,
uploadError,
handleFileUpload,
};
}