🚧 Switch to monorepo with Turbo
This commit is contained in:
40
apps/website/src/routes/api/newsletter/+server.ts
Normal file
40
apps/website/src/routes/api/newsletter/+server.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { NEWSLETTER_API_TOKEN, NEWSLETTER_LIST_ID } from '$env/static/private'
|
||||
import type { RequestHandler } from './$types'
|
||||
|
||||
export const POST = (async ({ request, fetch }) => {
|
||||
const data: { email: string } = await request.json()
|
||||
const { email } = data
|
||||
|
||||
// No email
|
||||
if (!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 new Response(JSON.stringify({ message: 'INVALID_EMAIL' }), { status: 400 })
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
// Other error
|
||||
if (res && res.status !== 'PENDING') {
|
||||
return new Response(JSON.stringify({ message: res.error.code }), { status: 400 })
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify({
|
||||
success: true,
|
||||
message: res.status,
|
||||
}), {
|
||||
status: 200
|
||||
})
|
||||
}) satisfies RequestHandler
|
||||
Reference in New Issue
Block a user