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

93 lines
2.6 KiB
TypeScript

import { type DetailedError, 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 TusFieldError {
message: string;
field: string;
rejectedValue: string;
}
interface TusErrorResponse {
timestamp: number[];
message: string;
status: number;
code: string;
errors: TusFieldError[];
}
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, response: TusErrorResponse | null) => 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, parseTusErrorResponse(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;
}
function parseTusErrorResponse(error: Error | DetailedError): TusErrorResponse | null {
if (!("originalResponse" in error)) return null;
const body = error.originalResponse?.getBody();
if (!body) return null;
try {
const parsed: unknown = JSON.parse(body);
if (typeof parsed !== "object" || parsed === null) return null;
if (typeof (parsed as TusErrorResponse).message !== "string") return null;
return parsed as TusErrorResponse;
} catch {
return null;
}
}
export { handleTusUpload };
export type { TusErrorResponse, TusUploadOptions };