From 4e96fbcd20a8ae93244634a7ba5bb8c2bf60eb46 Mon Sep 17 00:00:00 2001 From: Bas van den Aakster Date: Sun, 14 Sep 2025 21:06:47 +0200 Subject: [PATCH] Simplify sendEmail to rely on hooks for job creation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🔄 Cleaner Architecture: - sendEmail now just creates the email and lets hooks handle job creation - Hooks automatically create and populate job relationship - For processImmediately, retrieves job from relationship and runs it - Removes duplicate job creation logic from sendEmail 📈 Benefits: - Single source of truth for job creation (hooks) - Consistent behavior across all email creation methods - Simpler, more maintainable code - Better separation of concerns 🔍 Flow: 1. sendEmail creates email document 2. Hooks auto-create job and populate relationship 3. If processImmediately, fetch job from relationship and run it 4. Return email with complete job relationship --- src/sendEmail.ts | 55 ++++++++++++++++-------------------------------- 1 file changed, 18 insertions(+), 37 deletions(-) diff --git a/src/sendEmail.ts b/src/sendEmail.ts index d07f91a..d28f164 100644 --- a/src/sendEmail.ts +++ b/src/sendEmail.ts @@ -132,6 +132,7 @@ export const sendEmail = async setTimeout(resolve, 100)) + + // Refetch the email to get the populated jobs relationship + const emailWithJobs = await payload.findByID({ + collection: collectionSlug, + id: email.id, }) - jobId = String(job.id) - } catch (error) { - // Clean up the orphaned email since job creation failed - try { - await payload.delete({ - collection: collectionSlug, - id: email.id - }) - } catch (deleteError) { - console.error(`Failed to clean up orphaned email ${email.id} after job creation failure:`, deleteError) + if (!emailWithJobs.jobs || emailWithJobs.jobs.length === 0) { + throw new Error(`No processing job found for email ${email.id}. The auto-scheduling may have failed.`) } - // Throw the original job creation error - const errorMsg = `Failed to create processing job for email ${email.id}: ${String(error)}` - throw new Error(errorMsg) - } + // Get the first job ID (should only be one for a new email) + const jobId = Array.isArray(emailWithJobs.jobs) + ? String(emailWithJobs.jobs[0]) + : String(emailWithJobs.jobs) - // If processImmediately is true, process the job now - if (options.processImmediately) { try { await processJobById(payload, jobId) } catch (error) { - // For immediate processing failures, we could consider cleanup, but the job exists and could be retried later - // So we'll leave the email and job in place for potential retry throw new Error(`Failed to process email ${email.id} immediately: ${String(error)}`) } }