Refactored pages/api/assignments to mongodb
This commit is contained in:
@@ -1,12 +1,12 @@
|
||||
// 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, getDoc, deleteDoc} 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);
|
||||
|
||||
@@ -26,15 +26,19 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {id} = req.query;
|
||||
|
||||
const snapshot = await getDoc(doc(db, "assignments", id as string));
|
||||
const snapshot = await db.collection("assignments").findOne({ _id: new ObjectId(id as string) });
|
||||
|
||||
res.status(200).json({...snapshot.data(), id: snapshot.id});
|
||||
if (snapshot) {
|
||||
res.status(200).json({...snapshot, id: snapshot._id});
|
||||
}
|
||||
}
|
||||
|
||||
async function DELETE(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {id} = req.query;
|
||||
|
||||
await deleteDoc(doc(db, "assignments", id as string));
|
||||
await db.collection("assignments").deleteOne(
|
||||
{ _id: new ObjectId(id as string) }
|
||||
);
|
||||
|
||||
res.status(200).json({ok: true});
|
||||
}
|
||||
@@ -42,7 +46,10 @@ async function DELETE(req: NextApiRequest, res: NextApiResponse) {
|
||||
async function PATCH(req: NextApiRequest, res: NextApiResponse) {
|
||||
const {id} = req.query;
|
||||
|
||||
await setDoc(doc(db, "assignments", id as string), {assigner: req.session.user?.id, ...req.body}, {merge: true});
|
||||
await db.collection("assignments").updateOne(
|
||||
{ _id: new ObjectId(id as string) },
|
||||
{ $set: {assigner: req.session.user?.id, ...req.body} }
|
||||
);
|
||||
|
||||
res.status(200).json({ok: true});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user