owltide/server/api/auth/account.patch.ts

74 lines
2.1 KiB
TypeScript
Raw Normal View History

2025-03-07 22:28:55 +01:00
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,
});
}
}
if (patch.locale?.length) {
const locale = DateTime.local({ locale: patch.locale }).resolvedLocaleOptions().locale;
if (locale !== patch.locale) {
throw createError({
status: 400,
message: `Invalid locale: the locale "${patch.locale}" is not supported (was treated as "${locale}")`
});
}
}
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;
}
if (patch.locale !== undefined) {
if (patch.locale)
sessionAccount.locale = patch.locale;
else
delete sessionAccount.locale;
}
await writeAccounts(accounts);
2025-03-07 22:28:55 +01:00
// Update Schedule counts.
await updateScheduleInterestedCounts(accounts);
})