102 lines
2.5 KiB
JavaScript
102 lines
2.5 KiB
JavaScript
import response from "../response.js";
|
|
import models from "../models/index.js";
|
|
import bcrypt from "bcrypt";
|
|
|
|
export const getUsers = async (req, res) => {
|
|
try {
|
|
const users = await models.User.findAll({
|
|
attributes: {
|
|
exclude: ["password"],
|
|
},
|
|
});
|
|
response(200, users, "Success", res);
|
|
} catch (error) {
|
|
console.log(error);
|
|
response(500, null, "Error retrieving users data!", res);
|
|
}
|
|
};
|
|
|
|
export const getUserById = async (req, res) => {
|
|
try {
|
|
const { id } = req.params;
|
|
const user = await models.User.findByPk(id, {
|
|
attributes: {
|
|
exclude: ["password"],
|
|
},
|
|
});
|
|
|
|
if (!user) {
|
|
return response(404, null, "User not found", res);
|
|
}
|
|
|
|
response(200, user, "Success", res);
|
|
} catch (error) {
|
|
console.log(error);
|
|
res.status(500).json({ message: "Internal Server Error" });
|
|
}
|
|
};
|
|
|
|
export const updateUserById = async (req, res) => {
|
|
try {
|
|
const { id } = req.params;
|
|
const { name, email, password, roles } = req.body;
|
|
|
|
// Find the user by ID
|
|
const user = await models.User.findByPk(id);
|
|
|
|
if (!user) {
|
|
return response(404, null, "User not found", res);
|
|
}
|
|
|
|
// Check if the email is unique if it is being updated
|
|
if (email && email !== user.email) {
|
|
const emailExists = await models.User.findOne({ where: { email } });
|
|
if (emailExists) {
|
|
return response(400, null, "Email already in use", res);
|
|
}
|
|
user.email = email;
|
|
}
|
|
|
|
// Hash the password if it is being updated
|
|
if (password) {
|
|
const salt = await bcrypt.genSalt(10);
|
|
user.password = await bcrypt.hash(password, salt);
|
|
}
|
|
|
|
// Update other user information
|
|
user.name = name || user.name;
|
|
user.roles = roles || user.roles;
|
|
|
|
// Manually update the updated_at field
|
|
user.updated_at = new Date();
|
|
|
|
// Save the updated user information
|
|
await user.save();
|
|
|
|
response(200, user, "User updated successfully", res);
|
|
} catch (error) {
|
|
console.log(error);
|
|
res.status(500).json({ message: "Internal Server Error" });
|
|
}
|
|
};
|
|
|
|
export const deleteUserById = async (req, res) => {
|
|
try {
|
|
const { id } = req.params;
|
|
|
|
// Find the user by ID
|
|
const user = await models.User.findByPk(id);
|
|
|
|
if (!user) {
|
|
return response(404, null, "User not found", res);
|
|
}
|
|
|
|
// Delete the user
|
|
await user.destroy();
|
|
|
|
response(200, null, "User deleted successfully", res);
|
|
} catch (error) {
|
|
console.log(error);
|
|
res.status(500).json({ message: "Internal Server Error" });
|
|
}
|
|
}; |