Separate get exam bussiness logic into a backend asset
This commit is contained in:
@@ -1,14 +1,11 @@
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {app} from "@/firebase";
|
||||
import {getFirestore, collection, getDocs, query, where, setDoc, doc} from "firebase/firestore";
|
||||
import {getFirestore, setDoc, doc} from "firebase/firestore";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {shuffle} from "lodash";
|
||||
import {Exam} from "@/interfaces/exam";
|
||||
import {Stat} from "@/interfaces/user";
|
||||
import {v4} from "uuid";
|
||||
|
||||
import { getExams } from "@/utils/exams.be";
|
||||
const db = getFirestore(app);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
@@ -26,31 +23,12 @@ async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
return;
|
||||
}
|
||||
|
||||
const {module, avoidRepeated} = req.query as {module: string; avoidRepeated: string};
|
||||
const moduleRef = collection(db, module);
|
||||
|
||||
const q = query(moduleRef, where("isDiagnostic", "==", false));
|
||||
const snapshot = await getDocs(q);
|
||||
|
||||
const exams: Exam[] = shuffle(
|
||||
snapshot.docs.map((doc) => ({
|
||||
id: doc.id,
|
||||
...doc.data(),
|
||||
module,
|
||||
})),
|
||||
) as Exam[];
|
||||
|
||||
if (avoidRepeated === "true") {
|
||||
const statsQ = query(collection(db, "stats"), where("user", "==", req.session.user.id));
|
||||
const statsSnapshot = await getDocs(statsQ);
|
||||
|
||||
const stats: Stat[] = statsSnapshot.docs.map((doc) => ({id: doc.id, ...doc.data()})) as unknown as Stat[];
|
||||
const filteredExams = exams.filter((x) => !stats.map((s) => s.exam).includes(x.id));
|
||||
|
||||
res.status(200).json(filteredExams.length > 0 ? filteredExams : exams);
|
||||
return;
|
||||
}
|
||||
const {
|
||||
module,
|
||||
avoidRepeated,
|
||||
} = req.query as {module: string; avoidRepeated: string};
|
||||
|
||||
const exams: Exam[] = await getExams(db, module, avoidRepeated, req.session.user.id);
|
||||
res.status(200).json(exams);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user