email.ts•1.9 kB
import { env } from 'cloudflare:workers'
import { z } from 'zod'
const resendErrorSchema = z.union([
z.object({
name: z.string(),
message: z.string(),
statusCode: z.number(),
}),
z.object({
name: z.literal('UnknownError'),
message: z.literal('Unknown Error'),
statusCode: z.literal(500),
cause: z.any(),
}),
])
type ResendError = z.infer<typeof resendErrorSchema>
const resendSuccessSchema = z.object({
id: z.string(),
})
export async function sendEmail(options: {
to: string
subject: string
html: string
text: string
}) {
const from = 'hello@epicme.epicai.pro'
const email = {
from,
...options,
}
if (!env.RESEND_API_KEY || env.MOCKS === 'true') {
if (env.MOCKS === 'true') {
console.log(`In mocks mode.`)
}
if (!env.RESEND_API_KEY) {
console.log(`RESEND_API_KEY not set.`)
}
console.log(
`To send emails, set the RESEND_API_KEY environment variable and remove MOCKS env var.`,
)
console.log(`Would have sent the following email:`, JSON.stringify(email))
return {
status: 'success',
data: { id: 'mocked' },
} as const
}
const response = await fetch('https://api.resend.com/emails', {
method: 'POST',
body: JSON.stringify(email),
headers: {
Authorization: `Bearer ${env.RESEND_API_KEY}`,
'Content-Type': 'application/json',
},
})
const data = await response.json()
const parsedData = resendSuccessSchema.safeParse(data)
if (response.ok && parsedData.success) {
return {
status: 'success',
data: parsedData,
} as const
} else {
const parseResult = resendErrorSchema.safeParse(data)
if (parseResult.success) {
return {
status: 'error',
error: parseResult.data,
} as const
} else {
return {
status: 'error',
error: {
name: 'UnknownError',
message: 'Unknown Error',
statusCode: 500,
cause: data,
} satisfies ResendError,
} as const
}
}
}