Implement transaction handling in event deletion: Enhance deleteEvent function to manage foreign key constraints by removing associated EventContactPerson records before deleting the event. This ensures data integrity and improves error handling during the deletion process.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
const { Event, Institution, EventPlace, ContactPerson, EventType } = require('../models');
|
||||
const { Event, Institution, EventPlace, ContactPerson, EventType, EventContactPerson, sequelize } = require('../models');
|
||||
const { Op } = require('sequelize');
|
||||
const { startOfDay } = require('date-fns');
|
||||
|
||||
@@ -163,17 +163,28 @@ const updateEvent = async (req, res) => {
|
||||
};
|
||||
|
||||
const deleteEvent = async (req, res) => {
|
||||
const transaction = await sequelize.transaction();
|
||||
try {
|
||||
const { id } = req.params;
|
||||
// Erst Zuordnungen in der Join-Tabelle löschen, damit FK-Constraints erfüllt sind.
|
||||
await EventContactPerson.destroy({
|
||||
where: { event_id: id },
|
||||
transaction,
|
||||
});
|
||||
|
||||
const deleted = await Event.destroy({
|
||||
where: { id: id }
|
||||
where: { id: id },
|
||||
transaction,
|
||||
});
|
||||
if (deleted) {
|
||||
await transaction.commit();
|
||||
res.status(204).json();
|
||||
} else {
|
||||
await transaction.rollback();
|
||||
res.status(404).json({ error: 'Event not found' });
|
||||
}
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
res.status(500).json({ error: 'Failed to delete event' });
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user