Files
wondif_vue/server/api/parc-demandes.post.js
2026-04-21 18:39:01 +02:00

73 lines
1.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createError, readBody } from "h3"
import { getMysqlPool } from "~~/server/utils/mysql"
import { sendParcDemandEmails } from "~~/server/utils/mailer"
function normalizeValue(value) {
return typeof value === "string" ? value.trim() : ""
}
function isValidEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
}
export default defineEventHandler(async (event) => {
const body = await readBody(event)
const payload = {
requestType: normalizeValue(body?.requestType),
name: normalizeValue(body?.name),
email: normalizeValue(body?.email),
phone: normalizeValue(body?.phone),
organization: normalizeValue(body?.organization),
message: normalizeValue(body?.message),
}
if (!payload.requestType || !payload.name || !payload.email || !payload.phone || !payload.organization || !payload.message) {
throw createError({
statusCode: 400,
statusMessage: "Tous les champs obligatoires doivent être remplis.",
})
}
if (!isValidEmail(payload.email)) {
throw createError({
statusCode: 400,
statusMessage: "Ladresse email nest pas valide.",
})
}
if (payload.message.length > 5000) {
throw createError({
statusCode: 400,
statusMessage: "Le message est trop long.",
})
}
const db = getMysqlPool()
try {
const [result] = await db.execute(
`
INSERT INTO parc_demandes (type_demande, nom, email, telephone, organisme, message)
VALUES (?, ?, ?, ?, ?, ?)
`,
[payload.requestType, payload.name, payload.email, payload.phone, payload.organization, payload.message]
)
const emailsSent = await sendParcDemandEmails(payload)
return {
ok: true,
id: result.insertId,
emailsSent,
}
} catch (error) {
console.error("Erreur API parc-demandes:", error)
throw createError({
statusCode: 500,
statusMessage: "Impossible denregistrer la demande pour le moment.",
})
}
})