Refactor user storage and update

Rename accounts to users to be consistent with the new naming scheme
where account only referes to the logged in user of the session and
implement live updates of users via a user store which listens for
updates from the event stream.
This commit is contained in:
Hornwitser 2025-06-23 00:17:22 +02:00
parent 6336ccdb96
commit 3be7f8be05
24 changed files with 331 additions and 182 deletions

View file

@ -1,5 +1,5 @@
import { readAccounts, writeAccounts, nextAccountId } from "~/server/database";
import type { ApiAccount } from "~/shared/types/api";
import { readUsers, writeUsers, nextUserId, type ServerUser } from "~/server/database";
import { broadcastEvent } from "~/server/streams";
export default defineEventHandler(async (event) => {
let session = await getServerSession(event);
@ -13,8 +13,8 @@ export default defineEventHandler(async (event) => {
const formData = await readFormData(event);
const name = formData.get("name");
const accounts = await readAccounts();
let account: ApiAccount;
const users = await readUsers();
let user: ServerUser;
if (typeof name === "string") {
if (name === "") {
throw createError({
@ -22,22 +22,24 @@ export default defineEventHandler(async (event) => {
message: "Name cannot be blank",
});
}
if (accounts.some(account => account.name && account.name.toLowerCase() === name.toLowerCase())) {
if (users.some(user => user.name && user.name.toLowerCase() === name.toLowerCase())) {
throw createError({
status: 409,
message: "User already exists",
});
}
account = {
id: await nextAccountId(),
user = {
id: await nextUserId(),
updatedAt: new Date().toISOString(),
type: "regular",
name,
};
} else if (name === null) {
account = {
id: await nextAccountId(),
user = {
id: await nextUserId(),
updatedAt: new Date().toISOString(),
type: "anonymous",
};
} else {
@ -47,7 +49,11 @@ export default defineEventHandler(async (event) => {
});
}
accounts.push(account);
await writeAccounts(accounts);
await setServerSession(event, account.id);
users.push(user);
await writeUsers(users);
await broadcastEvent({
type: "user-update",
data: user,
});
await setServerSession(event, user);
})