import { Upload, type HttpResponse } from "tus-js-client"; import { getCookie, setCookie } from "@utils"; const AUTH_USER_ID = process.env.AUTH_USER_ID || ''; const CLAIM_NAME = process.env.CLAIM_NAME || ''; const BASE_URL = process.env.NEXT_PUBLIC_SERVER_API_URL || ''; const END_URL = `${BASE_URL}/attach-service/api/v1/tus/upload`; type UploadOptions = { handleUploadStart?: (upload: Upload) => void; handleProgress?: (percentage: string) => void; handleSuccess?: (upload: Upload) => void; handleResponse?: (res: HttpResponse) => void; }; export const handleUpload = (files: FileList, options?: UploadOptions) => { let metadata = {}; const file = files.item(0); if (!file) return; metadata = { filename: file.name, filetype: file.type, }; const upload = new Upload(file, { endpoint: END_URL, chunkSize: 10 * 1024 * 1024, headers: { [CLAIM_NAME]: getCookie(CLAIM_NAME) ?? "", [AUTH_USER_ID]: getCookie(AUTH_USER_ID) ?? "", }, metadata, onError(error) { console.error(`Failed because: ${error}`); }, onProgress(bytesUploaded, bytesTotal) { const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2); options?.handleProgress?.(percentage); }, onAfterResponse(req, res) { const fileInfo = res.getHeader("X-File-Info"); if (fileInfo === undefined || fileInfo === null) return; setCookie("atfl-cd-key", JSON.parse(fileInfo)?.atflCd ?? ""); options?.handleResponse?.(res); }, onSuccess() { options?.handleSuccess?.(upload); }, }); upload.start(); options?.handleUploadStart?.(upload); };