Improve type safety, error handling, and code maintainability

- Simplify sendEmail generic constraints for better type safety
- Add validation before type assertions in sendEmail
- Preserve error stack traces in sendEmailTask error handling
- Extract field copying logic into reusable helper function
- Improve code documentation and separation of concerns

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-09-13 23:06:02 +02:00
parent 790eedfee7
commit e7304fe1a2
2 changed files with 59 additions and 37 deletions

View File

@@ -4,7 +4,7 @@ import {Email, EmailTemplate} from "./payload-types.js"
import {BaseEmail} from "./types/index.js"
// Options for sending emails
export interface SendEmailOptions<T extends BaseEmail = BaseEmail> {
export interface SendEmailOptions<T extends Email = Email> {
// Template-based email
template?: {
slug: string
@@ -36,9 +36,9 @@ export interface SendEmailOptions<T extends BaseEmail = BaseEmail> {
* })
* ```
*/
export const sendEmail = async <TEmail extends Email = Email, TEmailTemplate extends EmailTemplate = EmailTemplate>(
export const sendEmail = async <TEmail extends Email = Email>(
payload: Payload,
options: SendEmailOptions<BaseEmail<TEmail, TEmailTemplate>>
options: SendEmailOptions<TEmail>
): Promise<TEmail> => {
const mailing = getMailing(payload)
const collectionSlug = options.collectionSlug || mailing.collections.emails || 'emails'
@@ -97,6 +97,11 @@ export const sendEmail = async <TEmail extends Email = Email, TEmailTemplate ext
data: emailData
})
// Validate that the created email has the expected structure
if (!email || typeof email !== 'object' || !email.id) {
throw new Error('Failed to create email: invalid response from database')
}
return email as TEmail
}