63 lines
1.9 KiB
TypeScript
63 lines
1.9 KiB
TypeScript
import axios from "axios";
|
|
import { playSound } from "@/utils/sound";
|
|
import { toast } from "react-toastify";
|
|
import { Generating } from "@/stores/examEditor/types";
|
|
import useExamEditorStore from "@/stores/examEditor";
|
|
import { Module } from "@/interfaces";
|
|
|
|
interface GeneratorConfig {
|
|
method: 'GET' | 'POST';
|
|
queryParams?: Record<string, string>;
|
|
body?: Record<string, any>;
|
|
}
|
|
|
|
export function generate(
|
|
sectionId: number,
|
|
module: Module,
|
|
type: "context" | "exercises",
|
|
config: GeneratorConfig,
|
|
mapData: (data: any) => Record<string, any>[]
|
|
) {
|
|
const dispatch = useExamEditorStore.getState().dispatch;
|
|
|
|
const setGenerating = (sectionId: number, generating: Generating) => {
|
|
dispatch({
|
|
type: "UPDATE_SECTION_SINGLE_FIELD",
|
|
payload: { sectionId, module, field: "generating", value: generating }
|
|
});
|
|
};
|
|
|
|
const setGeneratedExercises = (sectionId: number, exercises: Record<string, any>[] | undefined) => {
|
|
dispatch({
|
|
type: "UPDATE_SECTION_SINGLE_FIELD",
|
|
payload: { sectionId, module, field: "genResult", value: exercises }
|
|
});
|
|
};
|
|
|
|
setGenerating(sectionId, type);
|
|
|
|
const queryString = config.queryParams
|
|
? new URLSearchParams(config.queryParams).toString()
|
|
: '';
|
|
|
|
const url = `/api/exam/generate/${module}/${sectionId}${queryString ? `?${queryString}` : ''}`;
|
|
|
|
console.log(config.body);
|
|
|
|
const request = config.method === 'POST'
|
|
? axios.post(url, config.body)
|
|
: axios.get(url);
|
|
|
|
request
|
|
.then((result) => {
|
|
playSound("check");
|
|
setGeneratedExercises(sectionId, mapData(result.data));
|
|
})
|
|
.catch((error) => {
|
|
playSound("error");
|
|
toast.error("Something went wrong! Try to generate again.");
|
|
})
|
|
.finally(() => {
|
|
setGenerating(sectionId, undefined);
|
|
});
|
|
} |