Skip to content

Commit

Permalink
Added checks for unique email, contact & usernames
Browse files Browse the repository at this point in the history
when updating profile information
  • Loading branch information
ad956 committed Jul 6, 2024
1 parent 70bf991 commit 192d2f8
Showing 1 changed file with 56 additions and 6 deletions.
62 changes: 56 additions & 6 deletions app/api/patient/update-profile/personal/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,64 @@ type PersonalInfoBody = {
contact?: string;
};

export default async function PUT(req: Request) {
const email = "[email protected]";
export async function PUT(req: Request) {
const currentEmail = "[email protected]";

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];
}
});

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 }
);
Expand All @@ -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 }
);
}
}

0 comments on commit 192d2f8

Please sign in to comment.