From 85e32b757f49497630e0884975dfb05efc4822c6 Mon Sep 17 00:00:00 2001 From: Pedro Cardona <pedropca@stud.ntnu.no> Date: Tue, 28 Nov 2023 13:34:45 +0100 Subject: [PATCH] Change country endpoint was added --- controllers/user.controller.js | 22 ++++++++++++++++++++++ routes/user.router.js | 22 ++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/controllers/user.controller.js b/controllers/user.controller.js index 27d0548..9d2ef61 100644 --- a/controllers/user.controller.js +++ b/controllers/user.controller.js @@ -335,6 +335,27 @@ async function getUsersByPartialName(partialName) { } } +async function changeCountry(country, token) { + let client; + try { + client = await connectToDatabase(); + const db = client.db("TrioTech"); + const userCollection = db.collection("users"); + const id = await getUserId(token); + if (!id) throw new Error("Invalid user data"); + const user = await userCollection.findOne({ _id: new ObjectId(id) }); + if (!user) throw new Error("User not found"); + await userCollection.updateOne({ _id: new ObjectId(id) }, { $set: { country: country } }); + return true; + } catch (error) { + throw error; + } finally { + if (client) { + await client.close(); + } + } +} + module.exports = { createUser, getUser, @@ -345,4 +366,5 @@ module.exports = { changeAvatar, getActiveUser, getUsersByPartialName, + changeCountry, }; diff --git a/routes/user.router.js b/routes/user.router.js index 2eea741..5c3333b 100644 --- a/routes/user.router.js +++ b/routes/user.router.js @@ -411,4 +411,26 @@ router.get("/getUsers/:name", async (req, res) => { } }); +router.put("/changeCountry", async (req, res) => { + try { + if (await routersUtils.validateToken(res, req.cookies.jwt)) return; + if(!req.body.country) { + logger.warn("No country provided to change user country"); + return res.status(400).send("No country provided"); + } + logger.info("User id was requested successfully."); + res.status(200).send(await usersController.changeCountry(req.body.country, req.cookies.jwt)); + } catch (err) { + logger.error("User id was requested but failed with error: " + err); + let code = 500; + if (err.message == "Invalid user data") { + code = 400; + } + if (err.message == "User not found") { + code = 404; + } + res.status(code).send(err); + } +}); + module.exports = router; -- GitLab