Refactored pages/api/assignments to mongodb
This commit is contained in:
@@ -1,33 +1,37 @@
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {app} from "@/firebase";
|
||||
import {getFirestore, doc, getDoc, setDoc} from "firebase/firestore";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
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);
|
||||
|
||||
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 { id } = req.query as { id: string };
|
||||
const docSnap = await db.collection("assignments").findOne({ _id: new ObjectId(id) });
|
||||
|
||||
if (!docSnap.exists()) {
|
||||
res.status(404).json({ok: false});
|
||||
if (!docSnap) {
|
||||
res.status(404).json({ ok: false });
|
||||
return;
|
||||
}
|
||||
|
||||
await setDoc(docSnap.ref, {archived: false}, {merge: true});
|
||||
res.status(200).json({ok: true});
|
||||
await db.collection("assignments").updateOne(
|
||||
{ _id: new ObjectId(id) },
|
||||
{ $set: { archived: false } }
|
||||
);
|
||||
|
||||
res.status(200).json({ ok: true });
|
||||
return;
|
||||
}
|
||||
|
||||
res.status(401).json({ok: false});
|
||||
res.status(401).json({ ok: false });
|
||||
}
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
if (req.method === "POST") return post(req, res);
|
||||
res.status(404).json({ok: false});
|
||||
res.status(404).json({ ok: false });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user