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