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

82 lines
1.8 KiB
TypeScript

import type { APIRoute } from "astro";
import { prisma } from "../lib/prisma";
export const prerender = false;
export const POST: APIRoute = async ({ request }) => {
try {
const formData = await request.formData();
const nombre = formData.get("nombre")?.toString().trim();
const email = formData.get("email")?.toString().trim().toLowerCase();
const mensaje = formData.get("mensaje")?.toString().trim();
if (!nombre || !email || !mensaje) {
return new Response(
JSON.stringify({ error: "Datos incompletos" }),
{ status: 400 }
);
}
const now = new Date();
const startOfDay = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate()
);
const endOfDay = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() + 1
);
const existing = await prisma.contact.findUnique({
where: { email },
});
if (existing) {
// Si ya envió hoy → actualizar mensaje
if (existing.updatedAt >= startOfDay && existing.updatedAt < endOfDay) {
await prisma.contact.update({
where: { email },
data: {
nombre,
mensaje,
},
});
} else {
// Si es otro día → actualizar todo
await prisma.contact.update({
where: { email },
data: {
nombre,
mensaje,
},
});
}
} else {
await prisma.contact.create({
data: {
nombre,
email,
mensaje,
},
});
}
return new Response(null, {
status: 302,
headers: {
Location: "/?success=true",
},
});
} catch (error) {
console.error(error);
return new Response(null, {
status: 302,
headers: { Location: "/" },
});
}
};