Switch newsletter form to SvelteKit Form Actions

- remove api endpoint and use latest SK form actions
- create reusable server page function for form handling
- handling the errors in the server function
This commit is contained in:
2022-10-16 00:11:30 +02:00
parent b3616f9cff
commit 993dc90739
9 changed files with 142 additions and 75 deletions

View File

@@ -0,0 +1,49 @@
import { invalid } from '@sveltejs/kit'
import { NEWSLETTER_API_TOKEN, NEWSLETTER_LIST_ID } from '$env/static/private'
const formMessages = {
PENDING: `Almost there! Please confirm your email address through the email you'll receive soon.`,
MEMBER_EXISTS_WITH_EMAIL_ADDRESS: `This email address is already subscribed to the newsletter.`,
INVALID_EMAIL: `Woops. This email doesn't seem to be valid.`,
}
export default async ({ request }) => {
const formData = await request.formData()
const email = formData.get('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()
if (res) {
if (res && res.status !== 'PENDING') {
// Invalid email
if (!email.match(/^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)) {
return invalid(400, {
error: 'INVALID_EMAIL',
message () { return formMessages[this.error] }
})
}
// Other error
return invalid(400, {
error: res.error.code,
message: formMessages[res.error.code],
})
}
return {
success: true,
message: formMessages[res.status],
}
}
}