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)}`) } }