Files
housesof/src/utils/forms/subscribe.ts
Félix Péault 993dc90739 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
2022-10-16 00:11:30 +02:00

49 lines
1.6 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 { 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],
}
}
}