Refactored pages/api/assignments to mongodb

This commit is contained in:
Carlos Mesquita
2024-09-07 15:13:41 +01:00
parent e8b7c5ff80
commit 6f7ef1abef
14 changed files with 820 additions and 462 deletions

View File

@@ -1,16 +1,7 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { app, storage } from "@/firebase";
import {
getFirestore,
doc,
getDoc,
updateDoc,
getDocs,
query,
collection,
where,
documentId,
} from "firebase/firestore";
import client from "@/lib/mongodb";
import { ObjectId } from 'mongodb';
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
@@ -29,6 +20,7 @@ interface GroupScoreSummaryHelper {
}
interface AssignmentData {
_id: ObjectId;
assigner: string;
assignees: string[];
results: any;
@@ -41,7 +33,7 @@ interface AssignmentData {
name: string;
}
const db = getFirestore(app);
const db = client.db(process.env.MONGODB_DB);
export default withIronSessionApiRoute(handler, sessionOptions);
@@ -266,7 +258,7 @@ function commonExcel({
}),
`${Math.ceil(
data.stats.reduce((acc: number, curr: any) => acc + curr.timeSpent, 0) /
60
60
)} minutes`,
data.lastDate.format("DD/MM/YYYY HH:mm"),
data.correct,
@@ -392,9 +384,8 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
if (req.session.user) {
const { id } = req.query as { id: string };
const docSnap = await getDoc(doc(db, "assignments", id));
const data = docSnap.data() as AssignmentData;
if (!data) {
const assignment = await db.collection("assignments").findOne<AssignmentData>({ _id: new ObjectId(id) });
if (!assignment) {
res.status(400).end();
return;
}
@@ -411,19 +402,16 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
// return;
// }
const docsSnap = await getDocs(
query(collection(db, "users"), where(documentId(), "in", data.assignees))
);
const users = docsSnap.docs.map((d) => ({
...d.data(),
id: d.id,
})) as User[];
const objectIds = assignment.assignees.map(id => new ObjectId(id));
const docUser = await getDoc(doc(db, "users", data.assigner));
if (docUser.exists()) {
// we'll need the user in order to get the user data (name, email, focus, etc);
const user = docUser.data() as User;
const users = await db.collection("users").find({
_id: { $in: objectIds }
}).toArray() as User[] | null;
const user = await db.collection("users").findOne<User>({ _id: new ObjectId(assignment.assigner) });
// we'll need the user in order to get the user data (name, email, focus, etc);
if (user && users) {
// generate the file ref for storage
const fileName = `${Date.now().toString()}.xlsx`;
const refName = `assignment_report/${fileName}`;
@@ -433,11 +421,11 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
switch (user.type) {
case "teacher":
case "corporate":
return corporateAssignment(user as CorporateUser, data, users);
return corporateAssignment(user as CorporateUser, assignment, users);
case "mastercorporate":
return mastercorporateAssignment(
user as MasterCorporateUser,
data,
assignment,
users
);
default:
@@ -447,18 +435,24 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
const buffer = await getExcelFn();
// upload the pdf to storage
const snapshot = await uploadBytes(fileRef, buffer, {
await uploadBytes(fileRef, buffer, {
contentType:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
// update the stats entries with the pdf url to prevent duplication
await updateDoc(docSnap.ref, {
excel: {
path: refName,
version: process.env.EXCEL_VERSION,
},
});
await db.collection("assignments").updateOne(
{ _id: assignment._id },
{
$set: {
excel: {
path: refName,
version: process.env.EXCEL_VERSION,
}
}
}
);
const url = await getDownloadURL(fileRef);
res.status(200).end(url);