85 lines
2.1 KiB
TypeScript
85 lines
2.1 KiB
TypeScript
import { z } from 'zod'
|
|
|
|
const subscribeSchema = z.object({
|
|
email: z.string().email()
|
|
})
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const config = useRuntimeConfig()
|
|
|
|
// Validate request body
|
|
const body = await readBody(event)
|
|
const result = subscribeSchema.safeParse(body)
|
|
|
|
if (!result.success) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: 'Invalid email address'
|
|
})
|
|
}
|
|
|
|
const { email } = result.data
|
|
|
|
// Check if API key is configured
|
|
if (!config.brevoApiKey) {
|
|
console.error('BREVO_API_KEY is not configured')
|
|
throw createError({
|
|
statusCode: 500,
|
|
statusMessage: 'Newsletter service is not configured'
|
|
})
|
|
}
|
|
|
|
try {
|
|
// Build request body for Brevo Contacts API
|
|
const brevoBody: {
|
|
email: string
|
|
updateEnabled: boolean
|
|
listIds?: number[]
|
|
} = {
|
|
email,
|
|
updateEnabled: true
|
|
}
|
|
|
|
// Add list ID if configured
|
|
if (config.brevoNewsletterListId) {
|
|
const listId = parseInt(config.brevoNewsletterListId, 10)
|
|
if (!isNaN(listId)) {
|
|
brevoBody.listIds = [listId]
|
|
}
|
|
}
|
|
|
|
const response = await $fetch('https://api.brevo.com/v3/contacts', {
|
|
method: 'POST',
|
|
headers: {
|
|
'accept': 'application/json',
|
|
'api-key': config.brevoApiKey,
|
|
'content-type': 'application/json'
|
|
},
|
|
body: brevoBody
|
|
})
|
|
|
|
return {
|
|
success: true,
|
|
id: (response as { id?: number })?.id
|
|
}
|
|
} catch (error: unknown) {
|
|
// Handle Brevo API errors
|
|
const fetchError = error as { statusCode?: number; data?: { code?: string; message?: string } }
|
|
|
|
// Contact already exists (duplicate_parameter error) - treat as success
|
|
if (fetchError.data?.code === 'duplicate_parameter') {
|
|
return {
|
|
success: true,
|
|
message: 'Already subscribed'
|
|
}
|
|
}
|
|
|
|
console.error('Brevo API error:', fetchError.data || error)
|
|
|
|
throw createError({
|
|
statusCode: fetchError.statusCode || 500,
|
|
statusMessage: fetchError.data?.message || 'Failed to subscribe to newsletter'
|
|
})
|
|
}
|
|
})
|