Refactored codes
This commit is contained in:
@@ -1,12 +1,12 @@
|
|||||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||||
import type {NextApiRequest, NextApiResponse} from "next";
|
import type {NextApiRequest, NextApiResponse} from "next";
|
||||||
import {app} from "@/firebase";
|
import client from "@/lib/mongodb";
|
||||||
import {getFirestore, collection, getDocs, query, where, setDoc, doc, getDoc, deleteDoc} from "firebase/firestore";
|
import { ObjectId } from 'mongodb';
|
||||||
import {withIronSessionApiRoute} from "iron-session/next";
|
import {withIronSessionApiRoute} from "iron-session/next";
|
||||||
import {sessionOptions} from "@/lib/session";
|
import {sessionOptions} from "@/lib/session";
|
||||||
import {uuidv4} from "@firebase/util";
|
import {uuidv4} from "@firebase/util";
|
||||||
|
|
||||||
const db = getFirestore(app);
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||||
if (req.method === "GET") return GET(req, res);
|
if (req.method === "GET") return GET(req, res);
|
||||||
@@ -17,18 +17,17 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
|||||||
|
|
||||||
async function GET(req: NextApiRequest, res: NextApiResponse) {
|
async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const {id} = req.query;
|
const {id} = req.query;
|
||||||
|
const code = await db.collection("codes").findOne({ _id: new ObjectId(id as string) });
|
||||||
|
|
||||||
const snapshot = await getDoc(doc(db, "codes", id as string));
|
res.status(200).json(code);
|
||||||
|
|
||||||
res.status(200).json({...snapshot.data(), id: snapshot.id});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function DELETE(req: NextApiRequest, res: NextApiResponse) {
|
async function DELETE(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const {id} = req.query;
|
const {id} = req.query;
|
||||||
|
const code = await db.collection("codes").findOne({ _id: new ObjectId(id as string) });
|
||||||
|
|
||||||
const snapshot = await getDoc(doc(db, "codes", id as string));
|
if (!code) return res.status(404).json;
|
||||||
if (!snapshot.exists()) return res.status(404).json;
|
await db.collection("codes").deleteOne({ _id: new ObjectId(id as string) });
|
||||||
|
|
||||||
await deleteDoc(snapshot.ref);
|
res.status(200).json(code);
|
||||||
res.status(200).json({...snapshot.data(), id: snapshot.id});
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||||
import type { NextApiRequest, NextApiResponse } from "next";
|
import type { NextApiRequest, NextApiResponse } from "next";
|
||||||
import {app} from "@/firebase";
|
import client from "@/lib/mongodb";
|
||||||
import {getFirestore, setDoc, doc, query, collection, where, getDocs, getDoc, deleteDoc} from "firebase/firestore";
|
import { ObjectId } from 'mongodb';
|
||||||
import { withIronSessionApiRoute } from "iron-session/next";
|
import { withIronSessionApiRoute } from "iron-session/next";
|
||||||
import { sessionOptions } from "@/lib/session";
|
import { sessionOptions } from "@/lib/session";
|
||||||
import { Code, Group, Type } from "@/interfaces/user";
|
import { Code, Group, Type } from "@/interfaces/user";
|
||||||
import { PERMISSIONS } from "@/constants/userPermissions";
|
import { PERMISSIONS } from "@/constants/userPermissions";
|
||||||
import {uuidv4} from "@firebase/util";
|
|
||||||
import { prepareMailer, prepareMailOptions } from "@/email";
|
import { prepareMailer, prepareMailOptions } from "@/email";
|
||||||
|
|
||||||
const db = getFirestore(app);
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||||
|
|
||||||
@@ -28,10 +27,9 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { creator } = req.query as { creator?: string };
|
const { creator } = req.query as { creator?: string };
|
||||||
const q = query(collection(db, "codes"), where("creator", "==", creator || ""));
|
const snapshot = await db.collection("codes").find(creator ? { creator: creator } : {}).toArray();
|
||||||
const snapshot = await getDocs(creator ? q : collection(db, "codes"));
|
|
||||||
|
|
||||||
res.status(200).json(snapshot.docs.map((doc) => doc.data()));
|
res.status(200).json(snapshot);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||||
@@ -56,19 +54,12 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const codesGeneratedByUserSnapshot = await getDocs(query(collection(db, "codes"), where("creator", "==", req.session.user.id)));
|
const userCodes = await db.collection("codes").find<Code>({ creator: req.session.user.id }).toArray()
|
||||||
const creatorGroupsSnapshot = await getDocs(query(collection(db, "groups"), where("admin", "==", req.session.user.id)));
|
const creatorGroupsSnapshot = await db.collection("groups").find<Group>({ admin: req.session.user.id }).toArray()
|
||||||
|
|
||||||
const creatorGroups = (
|
|
||||||
creatorGroupsSnapshot.docs.map((x) => ({
|
|
||||||
...x.data(),
|
|
||||||
})) as Group[]
|
|
||||||
).filter((x) => x.name === "Students" || x.name === "Teachers" || x.name === "Corporate");
|
|
||||||
|
|
||||||
|
const creatorGroups = creatorGroupsSnapshot.filter((x) => x.name === "Students" || x.name === "Teachers" || x.name === "Corporate");
|
||||||
const usersInGroups = creatorGroups.flatMap((x) => x.participants);
|
const usersInGroups = creatorGroups.flatMap((x) => x.participants);
|
||||||
const userCodes = codesGeneratedByUserSnapshot.docs.map((x) => ({
|
|
||||||
...x.data(),
|
|
||||||
})) as Code[];
|
|
||||||
|
|
||||||
if (req.session.user.type === "corporate") {
|
if (req.session.user.type === "corporate") {
|
||||||
const totalCodes = userCodes.filter((x) => !x.userId || !usersInGroups.includes(x.userId)).length + usersInGroups.length + codes.length;
|
const totalCodes = userCodes.filter((x) => !x.userId || !usersInGroups.includes(x.userId)).length + usersInGroups.length + codes.length;
|
||||||
@@ -77,8 +68,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
if (totalCodes > allowedCodes) {
|
if (totalCodes > allowedCodes) {
|
||||||
res.status(403).json({
|
res.status(403).json({
|
||||||
ok: false,
|
ok: false,
|
||||||
reason: `You have or would have exceeded your amount of allowed codes, you currently are allowed to generate ${
|
reason: `You have or would have exceeded your amount of allowed codes, you currently are allowed to generate ${allowedCodes - userCodes.length
|
||||||
allowedCodes - codesGeneratedByUserSnapshot.docs.length
|
|
||||||
} codes.`,
|
} codes.`,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
@@ -86,7 +76,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const codePromises = codes.map(async (code, index) => {
|
const codePromises = codes.map(async (code, index) => {
|
||||||
const codeRef = doc(db, "codes", code);
|
const codeRef = await db.collection("codes").findOne<Code>({ _id: new ObjectId(code) });
|
||||||
let codeInformation = {
|
let codeInformation = {
|
||||||
type,
|
type,
|
||||||
code,
|
code,
|
||||||
@@ -114,16 +104,17 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
try {
|
try {
|
||||||
await transport.sendMail(mailOptions);
|
await transport.sendMail(mailOptions);
|
||||||
|
|
||||||
if (!previousCode) {
|
if (!previousCode && codeRef) {
|
||||||
await setDoc(
|
await db.collection("codes").updateOne(
|
||||||
codeRef,
|
{ _id: new ObjectId(codeRef._id) },
|
||||||
{
|
{
|
||||||
|
$set: {
|
||||||
...codeInformation,
|
...codeInformation,
|
||||||
email: email.trim().toLowerCase(),
|
email: email.trim().toLowerCase(),
|
||||||
name: name.trim(),
|
name: name.trim(),
|
||||||
...(passport_id ? { passport_id: passport_id.trim() } : {}),
|
...(passport_id ? { passport_id: passport_id.trim() } : {}),
|
||||||
},
|
}
|
||||||
{merge: true},
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,7 +123,12 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
await setDoc(codeRef, codeInformation);
|
// upsert: true -> if it doesnt exist insert
|
||||||
|
await db.collection("codes").updateOne(
|
||||||
|
{ _id: new ObjectId(code) },
|
||||||
|
{ $set: codeInformation },
|
||||||
|
{ upsert: true }
|
||||||
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -150,10 +146,10 @@ async function del(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
const codes = req.query.code as string[];
|
const codes = req.query.code as string[];
|
||||||
|
|
||||||
for (const code of codes) {
|
for (const code of codes) {
|
||||||
const snapshot = await getDoc(doc(db, "codes", code as string));
|
const snapshot = await db.collection("codes").findOne<Code>({ _id: new ObjectId(code as string) });
|
||||||
if (!snapshot.exists()) continue;
|
if (!snapshot) continue;
|
||||||
|
|
||||||
await deleteDoc(snapshot.ref);
|
await db.collection("codes").deleteOne({ _id: snapshot._id });
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(200).json({ codes });
|
res.status(200).json({ codes });
|
||||||
|
|||||||
Reference in New Issue
Block a user