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

@@ -3,6 +3,7 @@
</style>
<script lang="ts">
import { enhance } from '$app/forms'
import { fly } from 'svelte/transition'
import { quartOut } from 'svelte/easing'
import { sendEvent } from '$utils/analytics'
@@ -12,54 +13,40 @@
export let past: boolean = false
let inputInFocus = false
let formStatus: string = null
let formStatus: { error: string, success: boolean, message: string } = null
let formMessageTimeout: ReturnType<typeof setTimeout> | number
const formMessages = {
PENDING: `Almost there! Please confirm your email address through the email you'll receive soon.`,
MEMBER_EXISTS_WITH_EMAIL_ADDRESS: `Uh oh! 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
console.log(result.data)
/**
* Subscription form handling
*/
const formSubmission = async ({ target }) => {
const formData = new FormData(target)
const email = String(formData.get('email'))
if (email && email.match(/^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)) {
const req = await fetch('/api/newsletter', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: email
})
const res = await req.json()
formStatus = res.code
if (res.code === 'PENDING') {
// If successful
if (result.data.success) {
sendEvent({ action: 'newsletterSubscribe' })
}
update()
} else {
formStatus = 'INVALID_EMAIL'
}
}
$: if (formStatus !== 'PENDING') {
// Hide message for errors
clearTimeout(formMessageTimeout)
formMessageTimeout = setTimeout(() => formStatus = null, 3000)
formMessageTimeout = requestAnimationFrame(() => setTimeout(() => formStatus = null, 4000))
}
}
}
</script>
<div class="newsletter-form">
{#if formStatus !== 'PENDING'}
<form method="POST" on:submit|preventDefault={formSubmission}
out:fly={{ y: -8, easing: quartOut, duration: 600 }}
{#if !isSuccess}
<form method="POST" action="?/subscribe"
use:enhance={handleForm}
out:fly|local={{ y: -8, easing: quartOut, duration: 600 }}
>
<div class="newsletter-form__email" class:is-focused={inputInFocus}>
<input type="email" placeholder="Your email address" name="email" id="newsletter_email" required
@@ -90,14 +77,14 @@
</form>
{/if}
{#if formStatus}
{#if formStatus && formStatus.message}
<div class="newsletter-form__message shadow-small"
class:is-error={formStatus !== 'PENDING'}
class:is-success={formStatus === 'PENDING'}
in:fly={{ y: 8, easing: quartOut, duration: 600, delay: 600 }}
out:fly={{ y: 8, easing: quartOut, duration: 600 }}
class:is-error={!isSuccess}
class:is-success={isSuccess}
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">{formMessages[formStatus]}</p>
<p class="text-xsmall">{formStatus.message}</p>
</div>
{/if}
</div>

View File

@@ -7,7 +7,6 @@
import EmblaCarousel, { type EmblaCarouselType } from 'embla-carousel'
// Components
import Poster from '$components/molecules/Poster.svelte'
import EmailForm from '$components/molecules/EmailForm.svelte'
import { debounce } from '$utils/functions'
export let posters: any = []

View File

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

View File

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

View File

@@ -1,30 +0,0 @@
import { error } from '@sveltejs/kit'
import type { RequestHandler } from './$types'
import { NEWSLETTER_API_TOKEN, NEWSLETTER_LIST_ID } from '$env/static/private'
export const POST: RequestHandler = async ({ request }) => {
try {
const body = await request.text()
if (body) {
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: body,
})
})
const res = await req.json()
if (res) {
return new Response(JSON.stringify({
code: res.error ? res.error.code : res.status
}))
}
}
} catch (err) {
throw error(403, err.message)
}
}

View File

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

View File

@@ -1,9 +1,13 @@
import { error } from '@sveltejs/kit'
import type { PageServerLoad } from './$types'
import type { Actions, 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'
/**
* Page Data
*/
export const load: PageServerLoad = async ({ url, setHeaders }) => {
try {
// Query parameters
@@ -86,3 +90,12 @@ export const load: PageServerLoad = async ({ url, setHeaders }) => {
throw error(500, err.message)
}
}
/**
* Form Data
*/
export const actions: Actions = {
// Form newsletter subscription
subscribe,
}

View File

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

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],
}
}
}