60 lines
2.1 KiB
JavaScript
60 lines
2.1 KiB
JavaScript
import { Router } from 'express'
|
|
import { readFileSync, writeFileSync, existsSync } from 'fs'
|
|
import { join, dirname } from 'path'
|
|
import { fileURLToPath } from 'url'
|
|
import { Mutex } from 'async-mutex'
|
|
import { resourceLimiter } from '../middleware/rateLimiter.js'
|
|
import { antiSpam } from '../middleware/antiSpam.js'
|
|
import { sendSpeakerCv } from '../services/mailer.js'
|
|
|
|
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
const LEADS_FILE = join(__dirname, '..', 'data', 'speaker-cv-leads.json')
|
|
const PDF_PATH = join(__dirname, '..', '..', 'public', 'resources', 'speaker-cv-andre-knie.pdf')
|
|
const leadsMutex = new Mutex()
|
|
|
|
function loadLeads() {
|
|
if (!existsSync(LEADS_FILE)) return []
|
|
try { return JSON.parse(readFileSync(LEADS_FILE, 'utf-8')) }
|
|
catch { return [] }
|
|
}
|
|
|
|
function saveLeads(leads) {
|
|
writeFileSync(LEADS_FILE, JSON.stringify(leads, null, 2), 'utf-8')
|
|
}
|
|
|
|
const router = Router()
|
|
|
|
router.post('/', resourceLimiter, antiSpam, async (req, res) => {
|
|
const { name, email, message } = req.body
|
|
const errors = {}
|
|
if (!name || name.trim().length === 0) errors.name = 'Name ist erforderlich.'
|
|
if (name && name.length > 100) errors.name = 'Max. 100 Zeichen.'
|
|
if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) errors.email = 'Gültige E-Mail erforderlich.'
|
|
if (!message || message.trim().length === 0) errors.message = 'Bitte sag kurz, wer du bist.'
|
|
if (message && message.length > 2000) errors.message = 'Max. 2000 Zeichen.'
|
|
|
|
if (Object.keys(errors).length > 0) {
|
|
return res.status(400).json({ errors })
|
|
}
|
|
|
|
const lead = { name, email, message, timestamp: new Date().toISOString() }
|
|
try {
|
|
const result = await sendSpeakerCv(email, lead, PDF_PATH)
|
|
if (result.pdfMissing) {
|
|
return res.status(502).json({ error: 'Der Speaker CV ist derzeit nicht verfügbar.' })
|
|
}
|
|
|
|
await leadsMutex.runExclusive(async () => {
|
|
const leads = loadLeads()
|
|
leads.push(lead)
|
|
saveLeads(leads)
|
|
})
|
|
|
|
res.status(201).json({ ok: true, message: 'Danke! Der Speaker CV ist auf dem Weg in dein Postfach.' })
|
|
} catch {
|
|
res.status(503).json({ error: 'Der Versand ist derzeit nicht verfügbar.' })
|
|
}
|
|
})
|
|
|
|
export default router
|