Skip to content

Commit

Permalink
update user put endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
txingxie committed Jan 12, 2025
1 parent df90a2d commit 5bf0d7c
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
54 changes: 54 additions & 0 deletions api/src/controllers/userController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { Request, Response } from "express";
import User from "../model/User";

export const updateUser = async (req: Request, res: Response) => {
const { userId } = req.params;
const allowedFields = [
"firstName",
"lastName",
"username",
"email",
"role",
"workshopIDs",
"menteeInfo",
"meetingSchedule",
"mentorData",
"meetings",
];

try {
const updateData: Partial<typeof User> = {};
Object.keys(req.body).forEach((key) => {
if (allowedFields.includes(key)) {
updateData[key as keyof typeof updateData] = req.body[key];
}
});

if (Object.keys(updateData).length === 0) {
return res
.status(400)
.json({ message: "No valid fields provided for update" });
}

const updatedUser = await User.findByIdAndUpdate(
userId,
{ $set: updateData },
{ new: true, runValidators: true } // Return updated document and validate
);

if (!updatedUser) {
return res.status(404).json({ message: "User not found" });
}

res.status(200).json({
message: "User updated successfully",
user: updatedUser,
});
} catch (error) {
console.error("Error updating user:", error);
res.status(500).json({
message: "Error updating user",
error,
});
}
};
4 changes: 4 additions & 0 deletions api/src/routes/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import mongoose from "mongoose";
import dbConnect from "../config/db";
import sgMail from "@sendgrid/mail";
import User from "../model/User";
import { updateUser } from "../controllers/userController";
// import { validateAccessToken } from "../controllers/auth0-middleware";

const router = express.Router();
Expand Down Expand Up @@ -138,4 +139,7 @@ router.post("/add-meeting", async (req, res) => {
}
});

// Route to change a user's information
router.put("/:userId", updateUser);

export default router;

0 comments on commit 5bf0d7c

Please sign in to comment.