Files
encoach_frontend/src/pages/api/stats/index.ts
2024-10-10 19:13:18 +01:00

70 lines
2.2 KiB
TypeScript

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import client from "@/lib/mongodb";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { Stat } from "@/interfaces/user";
import { Assignment } from "@/interfaces/results";
import { groupBy } from "lodash";
import { requestUser } from "@/utils/api";
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);
if (req.method === "POST") return post(req, res);
}
async function get(req: NextApiRequest, res: NextApiResponse) {
const user = await requestUser(req, res)
if (!user) return res.status(401).json({ ok: false });
const snapshot = await db.collection("stats").find<Stat>({}).toArray();
res.status(200).json(snapshot);
}
async function post(req: NextApiRequest, res: NextApiResponse) {
const user = await requestUser(req, res)
if (!user) return res.status(401).json({ ok: false });
const stats = req.body as Stat[];
stats.forEach(async (stat) => await db.collection("stats").updateOne(
{ id: stat.id },
{ $set: stat },
{ upsert: true }
));
stats.forEach(async (stat) => {
await db.collection("sessions").deleteOne({ id: stat.session })
});
const groupedStatsByAssignment = groupBy(
stats.filter((x) => !!x.assignment),
"assignment",
);
if (Object.keys(groupedStatsByAssignment).length > 0) {
const assignments = Object.keys(groupedStatsByAssignment);
assignments.forEach(async (assignmentId) => {
const assignmentStats = groupedStatsByAssignment[assignmentId] as Stat[];
const assignmentSnapshot = await db.collection("assignments").findOne<Assignment>({ id: assignmentId });
await db.collection("assignments").updateOne(
{ id: assignmentId },
{
$set: {
results: [
...assignmentSnapshot ? assignmentSnapshot.results : [],
{ user: user.id, type: user.focus, stats: assignmentStats },
],
}
}
);
});
}
res.status(200).json({ ok: true });
}