Updated the register endpoint to use MongoDB
This commit is contained in:
@@ -2,30 +2,28 @@ import {collection, doc, getDoc, getDocs, getFirestore, query, setDoc, where} fr
|
||||
import {app} from "@/firebase";
|
||||
import {Group, Type, User} from "@/interfaces/user";
|
||||
import {uuidv4} from "@firebase/util";
|
||||
import client from "@/lib/mongodb";
|
||||
|
||||
const db = getFirestore(app);
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
export const addUserToGroupOnCreation = async (userId: string, type: Type, creatorId: string) => {
|
||||
const creatorDoc = await getDoc(doc(db, "users", creatorId));
|
||||
if (!creatorDoc.exists()) return false;
|
||||
const creator = await db.collection("users").findOne<User>({id: creatorId});
|
||||
if (!creator) return false;
|
||||
|
||||
const creator = {...creatorDoc.data(), id: creatorDoc.id} as User;
|
||||
const creatorGroup = await db.collection("groups").findOne<Group>({admin: creator.id, name: type === "student" ? "Students" : "Teachers"});
|
||||
|
||||
const creatorGroupsDocs = await getDocs(query(collection(db, "groups"), where("admin", "==", creator.id)));
|
||||
const typeGroup = creatorGroupsDocs.docs.find((x) => (x.data() as Group).name === (type === "student" ? "Students" : "Teachers"));
|
||||
|
||||
if (typeGroup && typeGroup.exists()) {
|
||||
await setDoc(typeGroup.ref, {participants: [...typeGroup.data().participants, userId]}, {merge: true});
|
||||
if (!!creatorGroup) {
|
||||
await db.collection("groups").updateOne({id: creatorGroup.id}, {$set: {participants: [...creatorGroup.participants, userId]}});
|
||||
return true;
|
||||
}
|
||||
|
||||
const groupId = uuidv4();
|
||||
await setDoc(doc(db, "groups", groupId), {
|
||||
await db.collection("groups").insertOne({
|
||||
admin: creatorId,
|
||||
name: type === "student" ? "Students" : "Teachers",
|
||||
id: groupId,
|
||||
participants: [userId],
|
||||
disableEditing: true,
|
||||
} as Group);
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user