User Routes
Course: PayTM project - chapter 8
1. Route to update user information
Section titled “1. Route to update user information”User should be allowed to optionally send either or all of
- password
- firstName
- lastName
Whatever they send, we need to update it in the database for the user.
Use the
middlewarewe defined in the last section to authenticate the user
Method: PUT Route: /api/v1/user Body:
{ password: "new_password", firstName: "updated_first_name", lastName: "updated_first_name",}Response:
Status code - 200
{ message: "Updated successfully"}Status code - 411 (Password is too small…)
{ message: "Error while updating information"}Solution
const { authMiddleware } = require("../middleware");
// other auth routes
const updateBody = zod.object({ password: zod.string().optional(), firstName: zod.string().optional(), lastName: zod.string().optional(),})
router.put("/", authMiddleware, async (req, res) => { const { success } = updateBody.safeParse(req.body) if (!success) { res.status(411).json({ message: "Error while updating information" }) }
await User.updateOne({ _id: req.userId }, req.body);
res.json({ message: "Updated successfully" })})2. Route to get users from the backend, filterable via firstName/lastName
Section titled “2. Route to get users from the backend, filterable via firstName/lastName”This is needed so users can search for their friends and send them money
Method: GET
Route: /api/v1/user/bulk
Query Parameter: ?filter=harkirat
Response:
Status code - 200
{ users: [{ firstName: "", lastName: "", _id: "id of the user" }]}Solution
router.get("/bulk", async (req, res) => { const filter = req.query.filter || "";
const users = await User.find({ $or: [{ firstName: { "$regex": filter } }, { lastName: { "$regex": filter } }] })
res.json({ user: users.map(user => ({ username: user.username, firstName: user.firstName, lastName: user.lastName, _id: user._id })) })})