Refactored pages/api/assignments to mongodb
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { app } from "@/firebase";
|
||||
import moment from "moment";
|
||||
import { getFirestore, doc, getDoc, setDoc } from "firebase/firestore";
|
||||
import client from "@/lib/mongodb";
|
||||
import { ObjectId } from 'mongodb';
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
|
||||
const db = getFirestore(app);
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
@@ -13,26 +13,25 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||
// verify if it's a logged user that is trying to archive
|
||||
if (req.session.user) {
|
||||
const { id } = req.query as { id: string };
|
||||
const docSnap = await getDoc(doc(db, "assignments", id));
|
||||
const data = await db.collection("assignments").findOne({ _id: new ObjectId(id) });
|
||||
|
||||
if (!docSnap.exists()) {
|
||||
if (!data) {
|
||||
res.status(404).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
|
||||
const data = docSnap.data();
|
||||
if (moment().isAfter(moment(data.startDate))) {
|
||||
res
|
||||
.status(400)
|
||||
.json({ ok: false, message: "Assignmentcan no longer " });
|
||||
.json({ ok: false, message: "Assignment can no longer " });
|
||||
return;
|
||||
}
|
||||
|
||||
await setDoc(
|
||||
docSnap.ref,
|
||||
{ start: true },
|
||||
{ merge: true }
|
||||
await db.collection("assignments").updateOne(
|
||||
{ _id: new ObjectId(id) },
|
||||
{ $set: { start: true } }
|
||||
);
|
||||
|
||||
res.status(200).json({ ok: true });
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user