90 lines
2.8 KiB
TypeScript
90 lines
2.8 KiB
TypeScript
import type { NextApiRequest, NextApiResponse } from "next";
|
|
import client from "@/lib/mongodb";
|
|
import { withIronSessionApiRoute } from "iron-session/next";
|
|
import { sessionOptions } from "@/lib/session";
|
|
import { UserSolution } from "@/interfaces/exam";
|
|
import { speakingReverseMarking, writingReverseMarking } from "@/utils/score";
|
|
import { Stat } from "@/interfaces/user";
|
|
|
|
const db = client.db(process.env.MONGODB_DB);
|
|
|
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
|
|
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
if (!req.session.user) {
|
|
res.status(401).json({ ok: false });
|
|
return;
|
|
}
|
|
try {
|
|
return await getSessionEvals(req, res);
|
|
} catch (error) {
|
|
console.error(error);
|
|
res.status(500).json({ ok: false });
|
|
}
|
|
}
|
|
|
|
function formatSolutionWithEval(userSolution: UserSolution | Stat, evaluation: any) {
|
|
if (userSolution.type === 'writing') {
|
|
return {
|
|
...userSolution,
|
|
solutions: [{
|
|
...userSolution.solutions[0],
|
|
evaluation: evaluation.result
|
|
}],
|
|
score: {
|
|
correct: writingReverseMarking[evaluation.result.overall],
|
|
total: 100,
|
|
missing: 0
|
|
},
|
|
isDisabled: false
|
|
};
|
|
}
|
|
|
|
if (userSolution.type === 'speaking' || userSolution.type === 'interactiveSpeaking') {
|
|
return {
|
|
...userSolution,
|
|
solutions: [{
|
|
...userSolution.solutions[0],
|
|
...(
|
|
userSolution.type === 'speaking'
|
|
? { fullPath: evaluation.result.fullPath }
|
|
: { answer: evaluation.result.answer }
|
|
),
|
|
evaluation: evaluation.result
|
|
}],
|
|
score: {
|
|
correct: speakingReverseMarking[evaluation.result.overall || 0] || 0,
|
|
total: 100,
|
|
missing: 0
|
|
},
|
|
isDisabled: false
|
|
};
|
|
}
|
|
|
|
return {
|
|
solution: userSolution,
|
|
evaluation
|
|
};
|
|
}
|
|
|
|
async function getSessionEvals(req: NextApiRequest, res: NextApiResponse) {
|
|
const { sessionId, userId, stats } = req.body;
|
|
const completedEvals = await db.collection("evaluation").find({
|
|
session_id: sessionId,
|
|
user: userId,
|
|
status: "completed"
|
|
}).toArray();
|
|
|
|
const evalsByExercise = new Map(
|
|
completedEvals.map(e => [e.exercise_id, e])
|
|
);
|
|
|
|
const statsWithEvals = stats
|
|
.filter((solution: UserSolution | Stat) => evalsByExercise.has(solution.exercise))
|
|
.map((solution: UserSolution | Stat) =>
|
|
formatSolutionWithEval(solution, evalsByExercise.get(solution.exercise)!)
|
|
);
|
|
|
|
res.status(200).json(statsWithEvals);
|
|
}
|