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 type { RequestHandler } from './$types'
import { error, json } from '@sveltejs/kit'
import { json } from '@sveltejs/kit'
export const POST = (async ({ request, fetch }) => {
const data: { email: string } = await request.json()
@@ -8,34 +8,34 @@ export const POST = (async ({ request, fetch }) => {
// No email
if (!email) {
throw error(400, { message: 'NO_EMAIL' })
return json({ message: 'NO_EMAIL' })
}
// Invalid email
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
// 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('server API response:', res)
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('server API response:', res)
// // Other error
// if (res && res.status !== 'PENDING') {
// throw error(400, { message: res.error.code })
// }
// Other error
if (res && res.status !== 'PENDING') {
return json({ message: res.error.code })
}
// return json({
// success: true,
// message: res.status,
// })
return json({
success: true,
message: res.status,
})
}) satisfies RequestHandler