ENCOA-274

This commit is contained in:
Carlos-Mesquita
2024-12-11 15:28:38 +00:00
parent 7538392e44
commit efba1939e5
12 changed files with 344 additions and 130 deletions

View File

@@ -8,6 +8,7 @@ import { Module } from "@/interfaces";
interface GeneratorConfig {
method: 'GET' | 'POST';
queryParams?: Record<string, string>;
files?: Record<string, string>;
body?: Record<string, any>;
}
@@ -66,18 +67,60 @@ export function generate(
const url = `/api/exam/generate/${module}/${sectionId}${queryString ? `?${queryString}` : ''}`;
const request = config.method === 'POST'
? axios.post(url, config.body)
: axios.get(url);
let body = null;
console.log(config.files);
if (config.files && Object.keys(config.files).length > 0 && config.method === 'POST') {
const formData = new FormData();
request
.then((result) => {
playSound("check");
setGeneratedResult(level ? levelSectionId! : sectionId, type, mapData(result.data), level);
})
.catch((error) => {
setGenerating(sectionId, undefined, level, true);
playSound("error");
toast.error("Something went wrong! Try to generate again.");
})
const buildForm = async () => {
await Promise.all(
Object.entries(config.files ?? {}).map(async ([key, blobUrl]) => {
const response = await fetch(blobUrl);
const blob = await response.blob();
const file = new File([blob], key, { type: blob.type });
formData.append(key, file);
})
);
if (config.body) {
Object.entries(config.body).forEach(([key, value]) => {
formData.append(key, value as string);
});
}
return formData;
};
buildForm().then(form => {
body = form;
const request = axios.post(url, body, { headers: { 'Content-Type': 'multipart/form-data' } });
request
.then((result) => {
playSound("check");
setGeneratedResult(level ? levelSectionId! : sectionId, type, mapData(result.data), level);
})
.catch((error) => {
setGenerating(sectionId, undefined, level, true);
playSound("error");
toast.error("Something went wrong! Try to generate again.");
});
});
} else {
body = config.body;
const request = config.method === 'POST'
? axios.post(url, body, { headers: { 'Content-Type': 'application/json' } })
: axios.get(url);
request
.then((result) => {
playSound("check");
setGeneratedResult(level ? levelSectionId! : sectionId, type, mapData(result.data), level);
})
.catch((error) => {
setGenerating(sectionId, undefined, level, true);
playSound("error");
toast.error("Something went wrong! Try to generate again.");
});
}
}