102 lines
2.9 KiB
JavaScript
102 lines
2.9 KiB
JavaScript
export default defineEventHandler(async (event) => {
|
|
try {
|
|
// Get notification ID from route parameters
|
|
const notificationId = getRouterParam(event, 'id')
|
|
|
|
if (!notificationId) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Notification ID is required'
|
|
})
|
|
}
|
|
|
|
// Get current user (assuming auth middleware provides this)
|
|
const user = event.context.user
|
|
if (!user) {
|
|
throw createError({
|
|
statusCode: 401,
|
|
statusMessage: 'Authentication required'
|
|
})
|
|
}
|
|
|
|
const { $db } = useNitroApp()
|
|
|
|
// Start transaction
|
|
await $db.query('BEGIN')
|
|
|
|
try {
|
|
// First, check if the notification exists and belongs to the user
|
|
const checkResult = await $db.query(
|
|
'SELECT id, title, status FROM notifications WHERE id = $1 AND created_by = $2',
|
|
[notificationId, user.id]
|
|
)
|
|
|
|
if (checkResult.rows.length === 0) {
|
|
throw createError({
|
|
statusCode: 404,
|
|
statusMessage: 'Notification not found or you do not have permission to delete it'
|
|
})
|
|
}
|
|
|
|
const notification = checkResult.rows[0]
|
|
|
|
// Check if notification can be deleted (only draft, scheduled, failed, or cancelled notifications)
|
|
const deletableStatuses = ['draft', 'scheduled', 'failed', 'cancelled']
|
|
if (!deletableStatuses.includes(notification.status)) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: `Cannot delete notification with status: ${notification.status}. Only draft, scheduled, failed, or cancelled notifications can be deleted.`
|
|
})
|
|
}
|
|
|
|
// Delete the notification (CASCADE will handle related records)
|
|
const deleteResult = await $db.query(
|
|
'DELETE FROM notifications WHERE id = $1 AND created_by = $2 RETURNING id, title',
|
|
[notificationId, user.id]
|
|
)
|
|
|
|
if (deleteResult.rows.length === 0) {
|
|
throw createError({
|
|
statusCode: 404,
|
|
statusMessage: 'Failed to delete notification'
|
|
})
|
|
}
|
|
|
|
// If notification was scheduled, remove it from queue
|
|
if (notification.status === 'scheduled') {
|
|
await $db.query(
|
|
'DELETE FROM notification_queue WHERE notification_id = $1',
|
|
[notificationId]
|
|
)
|
|
}
|
|
|
|
// Commit transaction
|
|
await $db.query('COMMIT')
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
id: notificationId,
|
|
title: notification.title,
|
|
message: 'Notification deleted successfully'
|
|
}
|
|
}
|
|
|
|
} catch (error) {
|
|
await $db.query('ROLLBACK')
|
|
throw error
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('Error deleting notification:', error)
|
|
|
|
if (error.statusCode) {
|
|
throw error
|
|
}
|
|
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: 'Failed to delete notification'
|
|
})
|
|
}
|
|
})
|