mirror of
https://github.com/xtr-dev/payload-mailing.git
synced 2025-12-10 08:13:23 +00:00
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:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user