Files
frontend/apps/as/src/entities/tus/lib/utils.ts
T

62 lines
1.8 KiB
TypeScript

import { Upload } from "tus-js-client";
import { ENDPOINT, PROXY_HOST } from "@/shared/config";
import { AUTH_USER_ID, CLAIM_NAME } from "@/shared/config/env";
import { getCookie } from "@/shared/lib";
interface TusUploadOptions {
metadata?: Record<string, string>;
handleUploadStart?: (upload: Upload) => void;
handleProgress?: (percentage: number) => void;
handleSuccess?: (upload: Upload, atflCd: string, atflId: string) => void;
handleError?: (error: Error) => void;
}
function handleTusUpload(file: File, options?: TusUploadOptions) {
let atflCd = "";
let atflId = "";
const metadata = {
filename: file.name,
filetype: file.type,
...options?.metadata,
};
const upload = new Upload(file, {
endpoint: `${PROXY_HOST}${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("TUS upload failed:", error);
options?.handleError?.(error);
},
onProgress(bytesUploaded, bytesTotal) {
const percentage = (bytesUploaded / bytesTotal) * 100;
options?.handleProgress?.(percentage);
},
onAfterResponse(_req, res) {
const fileInfo = res.getHeader("X-File-Info");
if (!fileInfo) return;
const parsed = JSON.parse(fileInfo) as { atflCd?: string; atflId?: string };
atflCd = parsed.atflCd ?? "";
atflId = parsed.atflId ?? "";
},
onSuccess() {
options?.handleSuccess?.(upload, atflCd, atflId);
},
});
upload.start();
options?.handleUploadStart?.(upload);
return upload;
}
export { handleTusUpload };
export type { TusUploadOptions };