owltide/server/api/modify-event.post.ts
Hornwitser 6ea3567c94 Refactor code saving data
Move the code dealing with saving and loading data to server/database to
gather it all up into one place.
2025-03-05 18:41:47 +01:00

37 lines
1.2 KiB
TypeScript

import { Schedule } from "~/shared/types/schedule";
import { broadcastUpdate } from "~/server/streams";
import { sendPush } from "~/server/web-push";
import { readSchedule, writeSchedule } from "~/server/database";
export default defineEventHandler(async (event) => {
const formData = await readFormData(event);
const schedule: Schedule = await readSchedule();
const id = formData.get("id") as string;
const name = formData.get("name") as string;
const description = formData.get("description") as string;
const start = formData.get("start") as string;
const end = formData.get("end") as string;
const location = formData.get("location") as string;
const index = schedule.events.findIndex(event => event.id === id);
if (index === -1) {
throw Error("No such event");
}
const timeChanged = schedule.events[index].slots[0].start !== start + "Z";
schedule.events[index] = {
name,
id,
description,
slots: [
{
id: `${id}-1`,
start: start + "Z",
end: end + "Z",
locations: [location],
}
]
};
broadcastUpdate(schedule);
await writeSchedule(schedule);
if (timeChanged)
await sendPush(`New time for ${name}`, `${name} will now start at ${start}`);
});