Switch to API route for newsletter form submission 🫠

not using the latest SvelteKit use:enhance thingy but… hey!
This commit is contained in:
2022-12-25 13:55:57 +01:00
parent c5791fa07c
commit 869debe87e
9 changed files with 66 additions and 121 deletions

View File

@@ -0,0 +1,37 @@
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 { email } = await request.json()
// No email
if (!email) {
throw error(400, { message: 'NO_EMAIL' })
}
// Invalid email
else if (!email || !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.json()
// 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