cdrdpyj/src/pages/api/emailPostulacion/send.ts

96 lines
2.3 KiB
TypeScript

import type { APIRoute } from "astro";
import { appendToSheet, emailExists } from "../lib/googleSheets";
export const prerender = false;
export const POST: APIRoute = async ({ request }) => {
try {
// 🔹 Leer datos del formulario
const formData = await request.formData();
const nombres = formData.get("nombres")?.toString().trim();
const apellidos = formData.get("apellidos")?.toString().trim();
const pais = formData.get("pais")?.toString().trim();
const lugar = formData.get("lugar")?.toString().trim();
const direccion = formData.get("direccion")?.toString().trim();
const telefono = formData.get("telefono")?.toString().trim();
const email = formData.get("email")?.toString().trim();
// 🔹 Validación básica
if (!nombres || !apellidos || !telefono || !email) {
return Response.redirect("/?error=datos", 303);
}
const exists = await emailExists(email);
if (exists) {
return Response.json({
success: false,
message: 'El email ya existe en la base de datos',
})
}
const dataSend = {
nombres,
apellidos,
pais,
lugar,
direccion,
telefono,
email
};
const emailApiKey = import.meta.env.EMAIL_API_KEY;
const valuesForSheets = [
nombres,
apellidos,
pais,
lugar,
direccion,
telefono,
email,
new Date().toLocaleString()
];
// 🔹 Enviar a tu backend real
const [emailResponse] = await Promise.all([
fetch("http://155.138.215.11:3050/email/send", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": emailApiKey!,
},
body: JSON.stringify({
type: "CENTRO_DEL_REINO_PAZ_Y_JUSTICIA_POSTULACION",
data: dataSend,
}),
}),
appendToSheet(valuesForSheets) // Guardar en Google Sheets
]);
if (!emailResponse.ok) {
return new Response(null, {
status: 302,
headers: {
Location: "/",
},
});
}
// 🔹 Redirección elegante después de enviar
return new Response(null, {
status: 302,
headers: {
Location: "/?success=true",
},
});
} catch (error) {
return new Response(null, {
status: 302,
headers: {
Location: "/",
},
});
}
};