111 lines
3.0 KiB
TypeScript
111 lines
3.0 KiB
TypeScript
import type { NextApiRequest, NextApiResponse } from "next";
|
|
import client from "@/lib/mongodb";
|
|
import { withIronSessionApiRoute } from "iron-session/next";
|
|
import { sessionOptions } from "@/lib/session";
|
|
|
|
const db = client.db(process.env.MONGODB_DB);
|
|
|
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
|
|
|
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
if (req.method === "GET") return get(req, res);
|
|
}
|
|
|
|
type Query = {
|
|
op: string;
|
|
sessionId: string;
|
|
userId: string;
|
|
}
|
|
|
|
async function get(req: NextApiRequest, res: NextApiResponse) {
|
|
if (!req.session.user) {
|
|
return res.status(401).json({ ok: false });
|
|
}
|
|
|
|
const { sessionId, userId, op } = req.query as Query;
|
|
|
|
switch (op) {
|
|
case 'pending':
|
|
return getPendingEvaluation(userId, sessionId, res);
|
|
case 'disabled':
|
|
return getSessionsWIthDisabledWithPending(userId, res);
|
|
default:
|
|
return res.status(400).json({
|
|
ok: false,
|
|
});
|
|
}
|
|
}
|
|
|
|
async function getPendingEvaluation(
|
|
userId: string,
|
|
sessionId: string,
|
|
res: NextApiResponse
|
|
) {
|
|
const singleEval = await db.collection("evaluation").findOne({
|
|
session_id: sessionId,
|
|
user: userId,
|
|
status: "pending",
|
|
});
|
|
return res.status(200).json({ hasPendingEvaluation: singleEval !== null });
|
|
}
|
|
|
|
async function getSessionsWIthDisabledWithPending(
|
|
userId: string,
|
|
res: NextApiResponse
|
|
) {
|
|
const sessions = await db.collection("stats")
|
|
.aggregate([
|
|
{
|
|
$match: {
|
|
user: userId,
|
|
disabled: true
|
|
}
|
|
},
|
|
{
|
|
$project: {
|
|
_id: 0,
|
|
session: 1
|
|
}
|
|
},
|
|
{
|
|
$lookup: {
|
|
from: "evaluation",
|
|
let: { sessionId: "$session" },
|
|
pipeline: [
|
|
{
|
|
$match: {
|
|
$expr: {
|
|
$and: [
|
|
{ $eq: ["$session", "$$sessionId"] },
|
|
{ $eq: ["$user", userId] },
|
|
{ $eq: ["$status", "pending"] }
|
|
]
|
|
}
|
|
}
|
|
},
|
|
{
|
|
$project: {
|
|
_id: 1
|
|
}
|
|
}
|
|
],
|
|
as: "pendingEvals"
|
|
}
|
|
},
|
|
{
|
|
$match: {
|
|
"pendingEvals.0": { $exists: true }
|
|
}
|
|
},
|
|
{
|
|
$group: {
|
|
id: "$session"
|
|
}
|
|
}
|
|
]).toArray();
|
|
|
|
return res.status(200).json({
|
|
sessions: sessions.map(s => s.id)
|
|
});
|
|
}
|