owltide/server/api/auth/account.patch.ts
Hornwitser fe06d0d6bd
All checks were successful
/ build (push) Successful in 2m5s
/ deploy (push) Successful in 16s
Refactor API types and sync logic
Rename and refactor the types passed over the API to be based on an
entity that's either living or a tombstone.  A living entity has a
deleted property that's either undefined or false, while a tombstone
has a deleted property set to true.  All entities have a numeric id
and an updatedAt timestamp.

To sync entities, an array of replacements are passed around. Living
entities are replaced with tombstones when they're deleted. And
tombstones are replaced with living entities when restored.
2025-06-11 21:05:17 +02:00

58 lines
1.7 KiB
TypeScript

import { readAccounts, writeAccounts } from "~/server/database";
import { DateTime } from "luxon";
import { apiAccountPatchSchema } from "~/shared/types/api";
import { z } from "zod/v4-mini";
export default defineEventHandler(async (event) => {
const session = await requireServerSession(event);
const { success, error, data: patch } = apiAccountPatchSchema.safeParse(await readBody(event));
if (!success) {
throw createError({
status: 400,
statusText: "Bad Request",
message: z.prettifyError(error),
});
}
if (patch.timezone?.length) {
const zonedTime = DateTime.local({ locale: "en-US" }).setZone(patch.timezone);
if (!zonedTime.isValid) {
throw createError({
status: 400,
message: "Invalid timezone: " + zonedTime.invalidExplanation,
});
}
}
const accounts = await readAccounts();
const sessionAccount = accounts.find(account => account.id === session.accountId);
if (!sessionAccount) {
throw Error("Account does not exist");
}
if (patch.interestedEventIds !== undefined) {
if (patch.interestedEventIds.length) {
sessionAccount.interestedEventIds = patch.interestedEventIds;
} else {
delete sessionAccount.interestedEventIds;
}
}
if (patch.interestedEventSlotIds !== undefined) {
if (patch.interestedEventSlotIds.length) {
sessionAccount.interestedEventSlotIds = patch.interestedEventSlotIds;
} else {
delete sessionAccount.interestedEventSlotIds;
}
}
if (patch.timezone !== undefined) {
if (patch.timezone)
sessionAccount.timezone = patch.timezone;
else
delete sessionAccount.timezone;
}
await writeAccounts(accounts);
// Update Schedule counts.
await updateScheduleInterestedCounts(accounts);
})