From 6b419495f7ac1aafa988e36c9be279fce64793cb Mon Sep 17 00:00:00 2001 From: Muhammad Afif Date: Fri, 10 Oct 2025 09:00:23 +0700 Subject: [PATCH] repair: roles controllers --- controllers/roles.controllers.js | 50 ++++++++++++-------------------- db/role.db.js | 2 +- 2 files changed, 19 insertions(+), 33 deletions(-) diff --git a/controllers/roles.controllers.js b/controllers/roles.controllers.js index 3f59d1b..aca1ff3 100644 --- a/controllers/roles.controllers.js +++ b/controllers/roles.controllers.js @@ -85,63 +85,49 @@ module.exports = { updateRoles: async (req, res, next) => { try { const { id } = req.params; - const { role_name, role_description, role_level } = req.body; - + const { role_name, role_description, role_level, updated_by } = req.body; + if (!id) { return res.status(400).json(setResponse(null, "Role ID is required", 400)); } - + const dataToUpdate = {}; + if (role_name) dataToUpdate.role_name = role_name; - + if (Object.prototype.hasOwnProperty.call(req.body, "role_description")) { dataToUpdate.role_description = role_description; } - + if (role_level !== undefined && role_level !== null) { const level = parseInt(role_level); if (isNaN(level)) { - return res.status(400).json( - setResponse( - null, - "role_level must be a number", - 400 - ) - ); + return res.status(400).json(setResponse(null, "role_level must be a number", 400)); } dataToUpdate.role_level = level; } - + + if (updated_by) dataToUpdate.updated_by = updated_by; + if (Object.keys(dataToUpdate).length === 0) { - return res.status(400).json( - setResponse( - null, - "No valid data provided for update", - 400 - ) - ); + return res.status(400).json(setResponse(null, "No valid data provided for update", 400)); } - + const existingRole = await roleDb.getRoleByIdDb(id); - if (!existingRole) { + if (!existingRole || existingRole.length === 0) { return res.status(404).json(setResponse(null, "Role not found", 404)); } - + await roleDb.updateRoleDb(id, dataToUpdate); - + const updatedRole = await roleDb.getRoleByIdDb(id); - - return res.status(200).json( - setResponse( - updatedRole, - "Role has been updated successfully", - 200 - ) - ); + + return res.status(200).json(setResponse(updatedRole, "Role has been updated successfully", 200)); } catch (err) { next(err); } }, + deleteRoles: async (req, res, next) => { try { diff --git a/db/role.db.js b/db/role.db.js index ccdfa2a..e49b110 100644 --- a/db/role.db.js +++ b/db/role.db.js @@ -46,7 +46,7 @@ const getRoleByIdDb = async (id) => { WHERE role_id = $1 AND deleted_at IS NULL `; const result = await pool.query(queryText, [id]); - return result.recordset[0]; + return result.recordset; }; // Create role