import { jsonError } from "../../../common.js"; export async function onRequestPost(context: RequestContext) { const { day, details, type } = context.data.body; const now = new Date(); const currentMonth = now.getUTCMonth(); const currentYear = now.getUTCFullYear(); if ( typeof day !== "number" || day < 1 || // Last day of that month day > new Date(currentYear, currentMonth, 0).getUTCDate() || // Stop people sending weird decimal days parseInt(day.toString()) !== day || typeof details !== "string" || !details.length || !["fotd", "gamenight", "rotw", "qotd"].includes(type) || (type === "rotw" && !context.data.body.answer) ) return jsonError("Invalid body", 400); if ( await context.env.D1.prepare( "SELECT * FROM events WHERE day = ? AND month = ? AND type = ? AND year = ?;", ) .bind(day, currentMonth, type, currentYear) .first() ) return jsonError( "Event with that type already exists for the specified date", 400, ); const id = `${now.getTime()}${crypto.randomUUID().replaceAll("-", "")}`; await context.env.D1.prepare( "INSERT INTO events (created_at, created_by, day, id, month, type, year) VALUES (?, ?, ?, ?, ?, ?, ?);", ) .bind( now.getTime(), context.data.current_user.id, day, id, currentMonth, type, currentYear, ) .run(); await context.env.DATA.put( `event_${id}`, JSON.stringify({ answer: context.data.body.answer, created_at: now.getTime(), created_by: context.data.current_user.id, day, details, month: currentMonth, pending: true, year: currentYear, }), { expirationTtl: 15552000, }, ); return new Response(null, { status: 204, }); }