inital commit
This commit is contained in:
76
controllers/institutionController.js
Normal file
76
controllers/institutionController.js
Normal file
@@ -0,0 +1,76 @@
|
||||
const { Institution, ContactPerson } = require('../models');
|
||||
|
||||
const getAllInstitutions = async (req, res) => {
|
||||
try {
|
||||
const institutions = await Institution.findAll({
|
||||
include: [
|
||||
{
|
||||
model: ContactPerson,
|
||||
as: 'contactPersons',
|
||||
through: { attributes: [] }
|
||||
}
|
||||
]
|
||||
});
|
||||
res.json(institutions);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to fetch institutions' });
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const createInstitution = async (req, res) => {
|
||||
try {
|
||||
const { contactPersonIds, ...institutionData } = req.body;
|
||||
const institution = await Institution.create(institutionData);
|
||||
if (contactPersonIds) {
|
||||
await institution.setContactPersons(contactPersonIds);
|
||||
}
|
||||
res.status(201).json(institution);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to create institution' });
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const updateInstitution = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const { contactPersonIds, ...institutionData } = req.body;
|
||||
const institution = await Institution.findByPk(id);
|
||||
if (!institution) {
|
||||
return res.status(404).json({ error: 'Institution not found' });
|
||||
}
|
||||
await institution.update(institutionData);
|
||||
if (contactPersonIds) {
|
||||
await institution.setContactPersons(contactPersonIds);
|
||||
}
|
||||
res.status(200).json(institution);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to update institution' });
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteInstitution = async (req, res) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const deleted = await Institution.destroy({
|
||||
where: { id: id }
|
||||
});
|
||||
if (deleted) {
|
||||
res.status(204).json();
|
||||
} else {
|
||||
res.status(404).json({ error: 'Institution not found' });
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Failed to delete institution' });
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
getAllInstitutions,
|
||||
createInstitution,
|
||||
updateInstitution,
|
||||
deleteInstitution
|
||||
};
|
||||
Reference in New Issue
Block a user