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

@@ -3,8 +3,6 @@
</style>
<script lang="ts">
import { enhance } from '$app/forms'
import { dev } from '$app/environment'
import { fly } from 'svelte/transition'
import { quartOut } from 'svelte/easing'
import { sendEvent } from '$utils/analytics'
@@ -15,27 +13,41 @@
export let past: boolean = false
let inputInFocus = false
let formStatus: { error: string, success: boolean, message: string } = null
let formStatus: FormStatus = null
let formMessageTimeout: ReturnType<typeof setTimeout> | number
interface FormStatus {
error?: string
success?: boolean
message: string
}
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.`,
}
$: isSuccess = formStatus && formStatus.success
// Toggle input focus
const toggleFocus = () => inputInFocus = !inputInFocus
// Handle form submission
const handleForm = () => {
return async ({ result, update }) => {
formStatus = result.data
async function handleForm (event: SubmitEvent) {
const data = new FormData(this)
const email = data.get('email')
console.log(result)
// if (dev) {
// }
if (email) {
const req = await fetch(this.action, {
method: 'POST',
body: JSON.stringify({ email })
})
const result: FormStatus = await req.json()
formStatus = result
// If successful
if (result.data.success) {
if (formStatus.success) {
sendEvent('newsletterSubscribe')
update()
} else {
// Hide message for errors
clearTimeout(formMessageTimeout)
@@ -47,8 +59,7 @@
<div class="newsletter-form">
{#if !isSuccess}
<form method="POST" action="?/subscribe"
use:enhance={handleForm}
<form method="POST" action="/api/newsletter" on:submit|preventDefault={handleForm}
out:fly|local={{ y: -8, easing: quartOut, duration: 600 }}
>
<div class="newsletter-form__email" class:is-focused={inputInFocus}>
@@ -87,7 +98,7 @@
in:fly|local={{ y: 8, easing: quartOut, duration: 600, delay: isSuccess ? 600 : 0 }}
out:fly|local={{ y: 8, easing: quartOut, duration: 600 }}
>
<p class="text-xsmall">{formStatus.message}</p>
<p class="text-xsmall">{formMessages[formStatus.message]}</p>
</div>
{/if}
</div>

View File

@@ -1,8 +1,7 @@
import { error } from '@sveltejs/kit'
import type { Actions, PageServerLoad } from './$types'
import type { PageServerLoad } from './$types'
import { PUBLIC_LIST_AMOUNT } from '$env/static/public'
import { fetchAPI, photoFields } from '$utils/api'
import subscribe from '$utils/forms/subscribe'
/**
@@ -93,12 +92,3 @@ export const load: PageServerLoad = async ({ params, setHeaders }) => {
throw error(500, err.message)
}
}
/**
* Form Data
*/
export const actions: Actions = {
// Form newsletter subscription
subscribe: subscribe,
}

View File

@@ -1,8 +0,0 @@
import type { Actions } from './$types'
import subscribe from '$utils/forms/subscribe'
export const actions: Actions = {
// Form newsletter subscription
subscribe: subscribe,
}

View File

@@ -1,8 +1,7 @@
import { error } from '@sveltejs/kit'
import type { Actions, PageServerLoad } from './$types'
import type { PageServerLoad } from './$types'
import { fetchAPI } from '$utils/api'
import { PUBLIC_FILTERS_DEFAULT_COUNTRY, PUBLIC_FILTERS_DEFAULT_SORT, PUBLIC_GRID_AMOUNT } from '$env/static/public'
import subscribe from '$utils/forms/subscribe'
/**
@@ -90,12 +89,3 @@ export const load: PageServerLoad = async ({ url, setHeaders }) => {
throw error(500, err.message)
}
}
/**
* Form Data
*/
export const actions: Actions = {
// Form newsletter subscription
subscribe: subscribe,
}

View File

@@ -1,7 +1,6 @@
import { error } from '@sveltejs/kit'
import type { Actions, PageServerLoad } from './$types'
import type { PageServerLoad } from './$types'
import { fetchAPI } from '$utils/api'
import subscribe from '$utils/forms/subscribe'
/**
@@ -41,12 +40,3 @@ export const load: PageServerLoad = async ({ setHeaders }) => {
throw error(500, err.message)
}
}
/**
* Form Data
*/
export const actions: Actions = {
// Form newsletter subscription
subscribe: subscribe,
}

View File

@@ -1,8 +1,7 @@
import { error } from '@sveltejs/kit'
import type { Actions, PageServerLoad } from './$types'
import type { PageServerLoad } from './$types'
import { fetchAPI } from '$utils/api'
import { getRandomItems } from '$utils/functions'
import subscribe from '$utils/forms/subscribe'
/**
@@ -58,12 +57,3 @@ export const load: PageServerLoad = async ({ setHeaders }) => {
throw error(500, err.message)
}
}
/**
* Form Data
*/
export const actions: Actions = {
// Form newsletter subscription
subscribe: subscribe,
}

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

View File

@@ -1,52 +0,0 @@
import { NEWSLETTER_API_TOKEN, NEWSLETTER_LIST_ID } from '$env/static/private'
import { fail } from '@sveltejs/kit'
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')
console.log(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()
console.log(res)
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 fail(400, {
error: 'INVALID_EMAIL',
message () { return formMessages[this.error] }
})
}
// Other error
return fail(400, {
error: res.error.code,
message: formMessages[res.error.code],
})
}
return {
success: true,
message: formMessages[res.status],
}
}
}

View File

@@ -17,9 +17,6 @@ const config = {
}),
kit: {
csrf: {
checkOrigin: false
},
adapter: adapter({
edge: true
}),