62 lines
1.7 KiB
TypeScript
62 lines
1.7 KiB
TypeScript
import { Upload, type HttpResponse } from "tus-js-client";
|
|
import { getCookie, setCookie } from "@/shared/lib";
|
|
import { AUTH_USER_ID, CLAIM_NAME, ENDPOINT } from "@/shared/config";
|
|
|
|
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 atflCd = getCookie("atfl-cd-key");
|
|
if (atflCd) {
|
|
metadata = {
|
|
...metadata,
|
|
atflCd,
|
|
};
|
|
}
|
|
|
|
const upload = new Upload(file, {
|
|
endpoint: `${ENDPOINT.ATTACH_SERVICE.TUS_UPLOAD}`,
|
|
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);
|
|
|
|
console.log("upload start >>>>>", upload);
|
|
};
|