diff --git a/app/lib/sync.ts b/app/lib/sync.ts index fb5d1a2..9a744ea 100644 --- a/app/lib/sync.ts +++ b/app/lib/sync.ts @@ -164,6 +164,23 @@ async function syncEmailsForDomainOptimized(domainId: number, bucket: string, s3 console.log(`To insert: ${toInsert.length}, To update: ${toUpdate.length}`); + // Finde und lösche E-Mails, die in der DB existieren aber nicht mehr in S3 + const toDelete = existingEmails + .filter(e => !allS3Keys.includes(e.s3Key)) + .map(e => e.s3Key); + + if (toDelete.length > 0) { + console.log(`Found ${toDelete.length} orphaned emails to delete from DB`); + try { + await db.delete(emails).where(inArray(emails.s3Key, toDelete)); + console.log(`Successfully deleted ${toDelete.length} orphaned emails`); + } catch (error) { + console.error('Error deleting orphaned emails:', error); + } + } else { + console.log('No orphaned emails found'); + } + if (toUpdate.length > 0) { const updateLimit = pLimit(CONCURRENT_S3_OPERATIONS); const updatePromises = toUpdate.map(key =>