81 lines
2.0 KiB
TypeScript
81 lines
2.0 KiB
TypeScript
import { UploadFileType } from "@model/questionTypes/file";
|
|
import { sendAnswer, sendFile } from "@api/quizRelase";
|
|
import { ACCEPT_SEND_FILE_TYPES_MAP, MAX_FILE_SIZE } from "@/components/ViewPublicationPage/tools/fileUpload";
|
|
|
|
export interface UploadFileOptions {
|
|
file: File;
|
|
questionId: string;
|
|
quizId: string;
|
|
fileType: UploadFileType;
|
|
preview: boolean;
|
|
onSuccess?: (fileUrl: string) => void;
|
|
onError?: (error: Error) => void;
|
|
onProgress?: (progress: number) => void;
|
|
}
|
|
|
|
export interface UploadFileResult {
|
|
success: boolean;
|
|
fileUrl?: string;
|
|
error?: Error;
|
|
}
|
|
|
|
export async function uploadFile({
|
|
file,
|
|
questionId,
|
|
quizId,
|
|
fileType,
|
|
preview,
|
|
onSuccess,
|
|
onError,
|
|
onProgress,
|
|
}: UploadFileOptions): Promise<UploadFileResult> {
|
|
try {
|
|
// Проверка размера файла
|
|
if (file.size > MAX_FILE_SIZE) {
|
|
const error = new Error("File is too big. Maximum size is 50 MB");
|
|
onError?.(error);
|
|
return { success: false, error };
|
|
}
|
|
|
|
// Проверка типа файла
|
|
const isFileTypeAccepted = ACCEPT_SEND_FILE_TYPES_MAP[fileType].some((fileType) =>
|
|
file.name.toLowerCase().endsWith(fileType)
|
|
);
|
|
|
|
if (!isFileTypeAccepted) {
|
|
const error = new Error("Incorrect file type selected");
|
|
onError?.(error);
|
|
return { success: false, error };
|
|
}
|
|
|
|
// Загрузка файла
|
|
const data = await sendFile({
|
|
questionId,
|
|
body: {
|
|
file,
|
|
name: file.name,
|
|
preview,
|
|
},
|
|
qid: quizId,
|
|
});
|
|
|
|
// Отправка ответа
|
|
await sendAnswer({
|
|
questionId,
|
|
body: `${data!.data.fileIDMap[questionId]}`,
|
|
qid: quizId,
|
|
preview,
|
|
});
|
|
|
|
const fileUrl = `${file.name}|${URL.createObjectURL(file)}`;
|
|
onSuccess?.(fileUrl);
|
|
onProgress?.(100);
|
|
|
|
return { success: true, fileUrl };
|
|
} catch (error) {
|
|
const err = error instanceof Error ? error : new Error("Unknown error occurred");
|
|
onError?.(err);
|
|
return { success: false, error: err };
|
|
}
|
|
}
|