owltide/server/api/auth/account.post.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

53 lines
1.2 KiB
TypeScript

import { readAccounts, writeAccounts, nextAccountId } from "~/server/database";
import type { ApiAccount } from "~/shared/types/api";
export default defineEventHandler(async (event) => {
let session = await getServerSession(event);
if (session) {
throw createError({
status: 409,
message: "Cannot create account while having an active session."
});
}
const formData = await readFormData(event);
const name = formData.get("name");
const accounts = await readAccounts();
let account: ApiAccount;
if (typeof name === "string") {
if (name === "") {
throw createError({
status: 400,
message: "Name cannot be blank",
});
}
if (accounts.some(account => account.name && account.name.toLowerCase() === name.toLowerCase())) {
throw createError({
status: 409,
message: "User already exists",
});
}
account = {
id: await nextAccountId(),
type: "regular",
name,
};
} else if (name === null) {
account = {
id: await nextAccountId(),
type: "anonymous",
};
} else {
throw createError({
status: 400,
message: "Invalid name",
});
}
accounts.push(account);
await writeAccounts(accounts);
await setServerSession(event, account.id);
})