- remove api endpoint and use latest SK form actions - create reusable server page function for form handling - handling the errors in the server function
49 lines
1.6 KiB
TypeScript
49 lines
1.6 KiB
TypeScript
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],
|
||
}
|
||
}
|
||
} |