Start the work of clearly distingushing client side types, server side types and types shared over the API by renaming "AccountSession" and "Session" names used on the server to "ServerSession".
53 lines
1.2 KiB
TypeScript
53 lines
1.2 KiB
TypeScript
import { readAccounts, writeAccounts, nextAccountId } from "~/server/database";
|
|
import { Account } from "~/shared/types/account";
|
|
|
|
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: Account;
|
|
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);
|
|
})
|