From 1a60b2550d9ed0f97ec83c9f076011ea8b01ebf2 Mon Sep 17 00:00:00 2001 From: Sanket Dhuri <121638042+arjunsudan@users.noreply.github.com> Date: Wed, 23 Oct 2024 23:56:49 +0530 Subject: [PATCH] route code refactor --- app/api/auth/register/route.js | 55 +++++++++++++++++++++++----------- app/api/chats/route.js | 49 ++++++++++-------------------- app/api/messages/route.js | 37 ++++++++--------------- 3 files changed, 65 insertions(+), 76 deletions(-) diff --git a/app/api/auth/register/route.js b/app/api/auth/register/route.js index 0fbd6a6..2db3501 100644 --- a/app/api/auth/register/route.js +++ b/app/api/auth/register/route.js @@ -2,41 +2,60 @@ import { connectToDB } from "@db/connect"; import User from "@models/UserModel"; import { hash } from "bcryptjs"; -export const POST = async (req, res) => { +export const POST = async (req) => { try { await connectToDB(); const { username, email, password } = await req.json(); + // Validate input fields + if (!username || !email || !password) { + return new Response( + JSON.stringify({ message: "All fields are required" }), + { + status: 400, + headers: { + "Content-Type": "application/json", + }, + } + ); + } + const existingUser = await User.findOne({ email }); if (existingUser) { - return new Response(JSON.stringify({ message: "User already exists" }), { - status: 400, - headers: { - "Content-Type": "application/json", - }, - }); + return new Response( + JSON.stringify({ message: "User already exists" }), + { + status: 400, + headers: { + "Content-Type": "application/json", + }, + } + ); } - const hashedPass = await hash(password, 10); + const hashedPassword = await hash(password, 10); - const newUser = await User.create({ + const newUser = new User({ username, email, - password: hashedPass, + password: hashedPassword, }); await newUser.save(); - return new Response(JSON.stringify(newUser), { - status: 200, - headers: { - "Content-Type": "application/json", - }, - }); - } catch (e) { - console.log(e); + return new Response( + JSON.stringify({ message: "User created successfully", user: newUser }), + { + status: 201, + headers: { + "Content-Type": "application/json", + }, + } + ); + } catch (error) { + console.error("Error creating user:", error); return new Response( JSON.stringify({ message: "Failed to create the new user" }), { diff --git a/app/api/chats/route.js b/app/api/chats/route.js index da329a2..ec75bf6 100644 --- a/app/api/chats/route.js +++ b/app/api/chats/route.js @@ -6,62 +6,43 @@ export const POST = async (req) => { try { await connectToDB(); - const body = await req.json(); - - // console.log(body); - - const { currentUserID, isGroup, members, groupPhoto, groupName } = body; + const { + currentUserID, + isGroup, + members, + groupPhoto, + groupName, + } = await req.json(); const query = isGroup ? { isGroup, groupPhoto, groupName, members: [currentUserID, ...members] } : { members: { $all: [currentUserID, ...members] }, $size: 2 }; - console.log(query); let chat = await Chat.findOne(query); - console.log("CHAT - ", chat); if (!chat) { chat = await Chat.create( isGroup ? query : { members: [currentUserID, ...members] } ); - // PUSH THE CHAT TO THE USER MODEL "CHAT" ARRAY - - - const updateAllMembers = chat.members.map( - async (memberID) => - await User.findByIdAndUpdate( + // Update all members' chat arrays + await Promise.all( + chat.members.map((memberID) => + User.findByIdAndUpdate( memberID, - { - $addToSet: { chats: chat._id }, - }, + { $addToSet: { chats: chat._id } }, { new: true } ) + ) ); - await Promise.all(updateAllMembers); } return new Response(JSON.stringify(chat), { status: 200 }); - - // if (!chat) { - // // THIS IS NOT CORRECT IG, WILL FIX IT LATER - // return new Response(JSON.stringify({ message: "Chat already exists" })); - // } else { - // chat = await Chat.create( - // isGroup ? query : { members: [currentUserID, ...members] } - // ); - - // // PUSH THE CHAT TO THE USER MODEL "CHAT" ARRAY - - // await User.findByIdAndUpdate(currentUserID, { - // $addToSet: { chats: chat._id }, - // }); - - // return new Response(JSON.stringify(chat), { status: 200 }); - // } } catch (err) { - console.log(err); + console.error("Error creating chat:", err); return new Response( JSON.stringify({ message: "Failed to create new chat" }), - { status: 500 } + { status: 500, headers: { "Content-Type": "application/json" } } ); } }; diff --git a/app/api/messages/route.js b/app/api/messages/route.js index 10bbbc1..151fba6 100644 --- a/app/api/messages/route.js +++ b/app/api/messages/route.js @@ -8,32 +8,26 @@ export const POST = async (req) => { try { await connectToDB(); - const body = await req.json(); - - const { chatID, currentUserID, text, photo } = body; + const { chatID, currentUserID, text, photo } = await req.json(); const currentUser = await User.findById(currentUserID); - - // console.log(body); - // console.log(chatID, currentUserID, text, photo); + if (!currentUser) { + return new Response(JSON.stringify({ message: "User not found" }), { status: 404 }); + } const newMessage = await Message.create({ chat: chatID, - sender: currentUser, + sender: currentUser._id, text, photos: photo, seenBy: [currentUserID], }); - // console.log(newMessage); - const updatedChat = await Chat.findByIdAndUpdate( chatID, { $push: { messages: newMessage._id }, - $set: { - lastMessage: newMessage.createdAt, - }, + $set: { lastMessage: newMessage.createdAt }, }, { new: true } ) @@ -41,14 +35,8 @@ export const POST = async (req) => { path: "messages", model: Message, populate: [ - { - path: "sender", - model: "User", - }, - { - path: "seenBy", - model: "User", - }, + { path: "sender", model: "User" }, + { path: "seenBy", model: "User" }, ], }) .populate({ @@ -57,13 +45,14 @@ export const POST = async (req) => { }) .exec(); - // console.log(updatedChat); - await pusherServer.trigger(chatID, "new-message", newMessage); return new Response(JSON.stringify(newMessage), { status: 200 }); } catch (error) { - console.log(error); - return new Response("Failed to create new message", { status: 500 }); + console.error("Error creating message:", error); + return new Response( + JSON.stringify({ message: "Failed to create new message" }), + { status: 500, headers: { "Content-Type": "application/json" } } + ); } };