File: //home/evaluation-leave/controllers/departmentController.js
const Department = require("../models/department");
module.exports = {
departments: async (req, res) => {
try {
const result = await Department.findAllDepartments();
if (!result) {
return res
.status(404)
.json({ message: "Sorry no Department has been setup." });
}
console.log(`Department, successfully pulled on ${new Date()} `);
return res.status(200).json(result);
} catch (error) {
console.error("Error occurred:", error);
res.status(500).json({ error: true, message: "Internal Server Error" });
}
},
departmentById: async (req, res) => {
const { id } = req.body;
try {
const result = await Department.findDepartmentById(id);
if (!result) {
return res
.status(404)
.json({ message: "Sorry that Department does not exist." });
}
console.log(
`Department with id ${id}, successfully pulled on ${new Date()} `
);
return res.status(200).json(result);
} catch (error) {
console.error("Error occurred:", error);
res.status(500).json({ error: true, message: "Internal Server Error" });
}
},
createDepartment: async (req, res) => {
const { name } = req.body;
try {
const serv = await Department.findDepartmentByName(name);
if (serv) {
return res.status(400).json({
message:
"Sorry there is an existing Department with that name. Choose a different name",
});
}
const newDepartment = { name };
const result = await Department.createDepartment(newDepartment);
console.log(`successfully Created a new Department on ${new Date()}`);
return res.status(201).json(result);
} catch (error) {
console.error("Error occurred:", error);
res.status(500).json({ error: true, message: "Internal Server Error" });
}
},
updateAvailableDepartment: async (req, res) => {
const { id, name } = req.body;
try {
const serv = await Department.findDepartmentById(id);
if (!serv) {
return res.status(400).json({
message: "Sorry there seems to be a problem. Try again latter",
});
}
const updatedDepartment = {
id,
name,
updated_by: req.userId,
updated_at: new Date(),
};
const result = await Department.updateDepartment(updatedDepartment);
console.log(
`Successfully Updated Deparment ${
updatedDepartment.name
} at ${new Date()}`
);
return res.status(201).json(result);
} catch (error) {
console.error("Error occurred:", error);
res.status(500).json({ error: true, message: "Internal Server Error" });
}
},
};