From 3a44d25402af211f6fd217533dcb818108479d1d Mon Sep 17 00:00:00 2001 From: felixtanhm Date: Thu, 9 May 2024 14:59:19 +0800 Subject: [PATCH] chore: remove default error messsage --- .../server/controllers/userController.js | 30 ++++++++++++++++--- .../server/routes/users.js | 2 ++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/full-stack-javascript/21-inventory-application/server/controllers/userController.js b/full-stack-javascript/21-inventory-application/server/controllers/userController.js index 7217300..3612ca2 100644 --- a/full-stack-javascript/21-inventory-application/server/controllers/userController.js +++ b/full-stack-javascript/21-inventory-application/server/controllers/userController.js @@ -2,12 +2,34 @@ const Users = require("../models/users"); exports.getUser = async function (req, res, next) { try { - const currUser = await Users.findOne({ email: "felixtanhm@gmail.com" }) - .populate("favorites") - .exec(); + const currUser = await Users.findOne({ + email: "felixtanhm@gmail.com", + }).exec(); res.status(200).json(currUser); } catch (error) { - return next(error); + next(error); + } +}; + +exports.updateUser = async function (req, res, next) { + try { + const { objectId, favorites } = req.body; + const updatedUser = await Users.updateOne( + { _id: objectId }, + { $set: { favorites: favorites } } + ); + + if (updatedUser.acknowledged) { + res.status(200).json(updatedUser); + } else { + const error = new Error( + "Something went wrong while saving your favorites!" + ); + error.status = 404; + return next(error); + } + } catch (error) { + next(error); } }; diff --git a/full-stack-javascript/21-inventory-application/server/routes/users.js b/full-stack-javascript/21-inventory-application/server/routes/users.js index af4333b..9e845a7 100644 --- a/full-stack-javascript/21-inventory-application/server/routes/users.js +++ b/full-stack-javascript/21-inventory-application/server/routes/users.js @@ -5,4 +5,6 @@ const userController = require("../controllers/userController"); /* GET users listing. */ router.get("/", userController.getUser); +router.post("/", userController.updateUser); + module.exports = router;