Always return json response and not error?

This commit is contained in:
2022-12-25 15:53:58 +01:00
parent 4f97e8bc8e
commit fd652da00a

View File

@@ -1,6 +1,6 @@
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 { error, json } from '@sveltejs/kit' 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,34 +8,34 @@ export const POST = (async ({ request, fetch }) => {
// No email // No email
if (!email) { if (!email) {
throw error(400, { message: 'NO_EMAIL' }) return json({ message: 'NO_EMAIL' })
} }
// 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-]+)*$/)) {
throw error(400, { message: 'INVALID_EMAIL' }) return json({ message: 'INVALID_EMAIL' })
} }
return json(email) // 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',
// headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ body: JSON.stringify({
// api_key: NEWSLETTER_API_TOKEN, api_key: NEWSLETTER_API_TOKEN,
// email_address: email, email_address: email,
// }) })
// }) })
// 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') {
// throw error(400, { message: res.error.code }) return json({ message: res.error.code })
// } }
// return json({ return json({
// success: true, success: true,
// message: res.status, message: res.status,
// }) })
}) satisfies RequestHandler }) satisfies RequestHandler