From 0c68bcf0ed9829107efa6bbd7802e0a100dd5d14 Mon Sep 17 00:00:00 2001 From: Hanen Alrwasheda <alrwasheda@mi.fu-berlin.de> Date: Mon, 3 Jan 2022 02:28:37 +0100 Subject: [PATCH] updateAccountById controller --- .../src/controllers/accounts.controllers.ts | 43 ++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/server/src/controllers/accounts.controllers.ts b/server/src/controllers/accounts.controllers.ts index 5b6da60..488f12d 100644 --- a/server/src/controllers/accounts.controllers.ts +++ b/server/src/controllers/accounts.controllers.ts @@ -64,7 +64,7 @@ const showAllAccounts = async (req: Request, res: Response) => { } }; -//show a specific account using given id: email is the primary key for a worker +//show a specific account using given id: email is the primary key for a worker const showAccountById = async (req: Request, res: Response) => { try { if (!(res.locals.user.role === "coordinator")) { @@ -83,10 +83,51 @@ const showAccountById = async (req: Request, res: Response) => { return res.status(500).json({ success: false, error: "serverError" }); } }; + +//update account by id +const updateAccount = async (req: Request, res: Response) => { + try { + if (!(res.locals.user.role === "coordinator")) { + return res + .status(403) + .json({ success: false, error: "MustBeCoordinator" }); + } + + //take what ever in req.body is, and pass it to update() + const input = req.body; //camelCase json + let givenId = req.params.id; + + //if given id not found + const worker = await Worker.findByPk(givenId); + if (!worker) { + return res.status(404).json({ success: false, error: "accountNotFound" }); + } + + //update worker + await Worker.update(input, { + where: { + email: givenId, //primary key in worker is email + }, + }); + + if (req.body.email !== "undefined") { + //if email was given in req.body -> update givenId (with new email) to find the updatedAccount and send its new data back + givenId = req.body.email; + } + + const updatedWorker = await Worker.findByPk(givenId); + return res.status(200).json({ success: true, result: updatedWorker }); + } catch (error) { + console.error("server error: ", error.message); + return res.status(500).json({ success: false, error: "serverError" }); + } +}; + const accountsControllers = { createAccountController, showAllAccounts, showAccountById, + updateAccount, }; export default accountsControllers; -- GitLab