Files
housesof/src/routes/api/newsletter/+server.ts
2022-12-25 14:43:57 +01:00

41 lines
1.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { NEWSLETTER_API_TOKEN, NEWSLETTER_LIST_ID } from '$env/static/private'
import type { RequestHandler } from './$types'
import { error } from '@sveltejs/kit'
export const POST = (async ({ request }) => {
const data = await request.json()
const { email } = data
console.log('server:', data, email)
// No email
if (!email) {
throw error(400, { message: 'NO_EMAIL' })
}
// Invalid email
if (!email.match(/^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)) {
throw error(400, { message: 'INVALID_EMAIL' })
}
// Newsletter API request
const req = await fetch(`https://emailoctopus.com/api/1.6/lists/${NEWSLETTER_LIST_ID}/contacts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
api_key: NEWSLETTER_API_TOKEN,
email_address: email,
})
})
const res = await req.text()
console.log('server:', res)
return new Response(res)
// Other error
if (res && res.status !== 'PENDING') {
throw error(400, { message: res.error.code })
}
return new Response(JSON.stringify({
success: true,
message: res.status,
}))
}) satisfies RequestHandler