Files
encoach_ui_odoo19/src/pages/api/evaluate/writing.ts
2024-12-28 03:30:15 +00:00

66 lines
1.7 KiB
TypeScript

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import axios from "axios";
import client from "@/lib/mongodb";
const db = client.db(process.env.MONGODB_DB);
interface Body {
userId: string;
sessionId: string;
question: string;
answer: string;
exerciseId: string;
task: 1 | 2;
}
export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) {
res.status(401).json({ ok: false });
return;
}
const body = req.body as Body;
const taskNumber = body.task.toString() !== "1" && body.task.toString() !== "2" ? "1" : body.task.toString();
// Check if there is one eval for the current exercise
const previousEval = await db.collection("evaluation").findOne({
user: body.userId,
session_id: body.sessionId,
exercise_id: body.exerciseId,
})
// If there is delete it
if (previousEval) {
await db.collection("evaluation").deleteOne({
user: body.userId,
session_id: body.sessionId,
exercise_id: body.exerciseId,
})
}
// Insert the new eval for the backend to place it's result
await db.collection("evaluation").insertOne(
{
user: body.userId,
session_id: body.sessionId,
exercise_id: body.exerciseId,
type: "writing",
task: body.task,
status: "pending"
}
);
await axios.post(`${process.env.BACKEND_URL}/grade/writing/${taskNumber}`, body, {
headers: {
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
},
});
res.status(200).json({ ok: true });
}