import { blob } from "https://esm.town/v/std/blob?v=10";
import { email } from "https://esm.town/v/std/email?v=11";
interface RSVP {
name: string;
email: string;
status?: "going" | "maybe";
}
export default async function(req: Request): Promise<Response> {
let rsvps = await blob.getJSON("rsvps") as RSVP[];
rsvps ??= [];
if (req.method === "GET") {
return new Response(JSON.stringify(rsvps.map(rsvp => ({ name: rsvp.name, status: rsvp.status ?? "going" }))), {
headers: { "content-type": "application/json" },
});
}
if (req.method === "POST") {
throw new Response("The event has already happened :^) no more RSVPSs");
const emails = rsvps.map(rsvp => rsvp.email);
const formData = await req.formData();
const name = formData.get("name") as string;
const email = formData.get("email") as string;
const status = formData.get("status") as ("going" | "maybe" | undefined) ?? "maybe";
if (emails.includes(email)) {
const rsvp = rsvps.find(rsvp => rsvp.email === email);
if (rsvp) {
rsvp.status = status;
await blob.setJSON("rsvps", rsvps);
return new Response(`Thanks! I've updated your RSVP status to ${status}.`);
}
}
if (!name || !email || !status) {
throw new Response("Missing name, email or status");
}
rsvps.push({ name, email });
await blob.setJSON("rsvps", rsvps);
return new Response("Thanks! You're signed up! I'll send you some reminders before the event :^)");
}
}