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.
53 lines
1.2 KiB
TypeScript
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);
|
|
})
|