Return Responses

This commit is contained in:
2022-12-25 16:08:09 +01:00
parent 5af12a39d7
commit f0018bead3

View File

@@ -1,6 +1,5 @@
import { NEWSLETTER_API_TOKEN, NEWSLETTER_LIST_ID } from '$env/static/private'
import type { RequestHandler } from './$types'
import { json } from '@sveltejs/kit'
export const POST = (async ({ request, fetch }) => {
const data: { email: string } = await request.json()
@@ -8,15 +7,13 @@ export const POST = (async ({ request, fetch }) => {
// No email
if (!email) {
return json({ message: 'NO_EMAIL' })
return new Response(JSON.stringify({ message: 'NO_EMAIL' }), { status: 400 })
}
// Invalid email
if (!email.match(/^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)) {
return json({ message: 'INVALID_EMAIL' })
return new Response(JSON.stringify({ message: 'INVALID_EMAIL' }), { status: 400 })
}
// return json(email)
// Newsletter API request
const req = await fetch(`https://emailoctopus.com/api/1.6/lists/${NEWSLETTER_LIST_ID}/contacts`, {
method: 'POST',
@@ -26,15 +23,12 @@ export const POST = (async ({ request, fetch }) => {
email_address: email,
})
})
try {
if (req.ok) {
const res = await req.json()
console.log('server API response:', res)
// Other error
if (res && res.status !== 'PENDING') {
return json({ message: res.error.code })
return new Response(JSON.stringify({ message: res.error.code }), { status: 400 })
}
return new Response(JSON.stringify({
@@ -43,8 +37,4 @@ export const POST = (async ({ request, fetch }) => {
}), {
status: 200
})
}
} catch (err) {
console.error(err)
}
}) satisfies RequestHandler