Assignments now generate unique list of exams for each user

This commit is contained in:
Joao Ramos
2023-12-07 18:23:00 +00:00
parent f7af21878e
commit 5eaa0ac269
3 changed files with 91 additions and 34 deletions

View File

@@ -5,6 +5,10 @@ import {getFirestore, collection, getDocs, query, where, setDoc, doc} from "fire
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {uuidv4} from "@firebase/util";
import { Module } from "@/interfaces";
import { getExams } from "@/utils/exams.be";
import { Exam } from "@/interfaces/exam";
import { flatten } from "lodash";
const db = getFirestore(app);
@@ -34,8 +38,65 @@ async function GET(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json(docs);
}
async function POST(req: NextApiRequest, res: NextApiResponse) {
await setDoc(doc(db, "assignments", uuidv4()), {assigner: req.session.user?.id, ...req.body});
res.status(200).json({ok: true});
interface ExamWithUser {
module: Module;
id: string;
assignee: string;
}
function getRandomIndex(arr: any[]): number {
const randomIndex = Math.floor(Math.random() * arr.length);
return randomIndex;
}
async function POST(req: NextApiRequest, res: NextApiResponse) {
const { selectedModules, assignees, ...body } = req.body as {
selectedModules: Module[];
assignees: string[];
};
// for optimization purposes, it would be better to create a new endpoint that returned the answers for all users at once
const allExams = await assignees.map(async (assignee) => {
const selectedModulePromises = await selectedModules.map(
async (module: Module) => {
try {
const exams: Exam[] = await getExams(db, module, "true", assignee);
const exam = exams[getRandomIndex(exams)];
if (exam) {
return { module: exam.module, id: exam.id, assignee };
}
return null;
} catch (e) {
console.error(e);
return null;
}
},
[]
);
const newModules = await Promise.all(selectedModulePromises);
return newModules;
}, []);
const exams = flatten(await Promise.all(allExams)).filter(
(x) => x !== null
) as ExamWithUser[];
if (exams.length === 0) {
res
.status(400)
.json({ ok: false, error: "No exams found for the selected modules" });
return;
}
await setDoc(doc(db, "assignments", uuidv4()), {
assigner: req.session.user?.id,
assignees,
results: [],
exams,
...body,
});
res.status(200).json({ ok: true });
}