From 192d2f809f1c94a670a6ee8c0bfd5720d6feb6cb Mon Sep 17 00:00:00 2001 From: Anand Suthar Date: Sun, 7 Jul 2024 00:20:54 +0530 Subject: [PATCH] Added checks for unique email, contact & usernames when updating profile information --- .../patient/update-profile/personal/route.ts | 62 +++++++++++++++++-- 1 file changed, 56 insertions(+), 6 deletions(-) diff --git a/app/api/patient/update-profile/personal/route.ts b/app/api/patient/update-profile/personal/route.ts index 8c7d35cd..3916728f 100644 --- a/app/api/patient/update-profile/personal/route.ts +++ b/app/api/patient/update-profile/personal/route.ts @@ -10,12 +10,12 @@ type PersonalInfoBody = { contact?: string; }; -export default async function PUT(req: Request) { - const email = "anandsuthar956@gmail.com"; +export async function PUT(req: Request) { + const currentEmail = "anandsuthar956@gmail.com"; const updateData: PersonalInfoBody = await req.json(); - // Remove undefined fields + // remove undefined fields Object.keys(updateData).forEach((key) => { if (updateData[key as keyof PersonalInfoBody] === undefined) { delete updateData[key as keyof PersonalInfoBody]; @@ -23,8 +23,51 @@ export default async function PUT(req: Request) { }); try { + // check for uniqueness of username, email, and contact + if (updateData.username) { + const existingUsername = await Patient.findOne({ + username: updateData.username, + email: { $ne: currentEmail }, + }); + if (existingUsername) { + return Response.json( + { error: "Username already exists" }, + { status: 400 } + ); + } + } + + if (updateData.email) { + const existingEmail = await Patient.findOne({ + email: updateData.email, + _id: { + $ne: await Patient.findOne({ email: currentEmail }).select("_id"), + }, + }); + if (existingEmail) { + return Response.json( + { error: "Email already exists" }, + { status: 400 } + ); + } + } + + if (updateData.contact) { + const existingContact = await Patient.findOne({ + contact: updateData.contact, + email: { $ne: currentEmail }, + }); + if (existingContact) { + return Response.json( + { error: "Contact number already exists" }, + { status: 400 } + ); + } + } + + // update the patient const updatedPatient = await Patient.findOneAndUpdate( - { email }, + { email: currentEmail }, { $set: updateData }, { new: true } ); @@ -33,8 +76,15 @@ export default async function PUT(req: Request) { return Response.json({ error: "Patient not found" }, { status: 404 }); } - return Response.json({ msg: "ok" }, { status: 200 }); + return Response.json( + { msg: "Profile updated successfully" }, + { status: 200 } + ); } catch (error) { - return Response.json({ error: "Error updating address" }, { status: 500 }); + console.error("Error updating patient information:", error); + return Response.json( + { error: "Failed to update personal information" }, + { status: 500 } + ); } }