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

84
stores/users.ts Normal file
View file

@ -0,0 +1,84 @@
import { Info } from "~/shared/utils/luxon";
import { defineStore } from 'pinia'
interface SyncOperation {
controller: AbortController,
promise: Promise<Ref<ClientMap<ClientUser>>>,
}
export const useUsersStore = defineStore("users", () => {
const accountStore = useAccountStore();
const state = {
fetched: ref<boolean>(false),
pendingSync: ref<SyncOperation>(),
users: ref<ClientMap<ClientUser>>(new ClientMap(ClientUser, new Map(), new Map())),
}
const getters = {
}
const actions = {
async fetch() {
if (state.fetched.value) {
return state.users;
}
const pending = state.pendingSync.value;
if (pending) {
return pending.promise;
}
const requestFetch = useRequestFetch();
const controller = new AbortController();
const zone = Info.normalizeZone(accountStore.activeTimezone);
const locale = accountStore.activeLocale;
const promise = (async () => {
try {
const apiUsers = await requestFetch("/api/users", { signal: controller.signal });
state.users.value.apiUpdate({
type: "user",
entities: apiUsers,
}, { zone, locale });
state.pendingSync.value = undefined;
state.fetched.value = true;
return state.users;
} catch (err: any) {
if (err.name !== "AbortError")
state.pendingSync.value = undefined;
throw err;
}
})();
state.pendingSync.value = {
controller,
promise,
};
return promise;
},
async resync(id: number) {
const pending = state.pendingSync.value;
if (pending) {
pending.controller.abort();
}
state.pendingSync.value = undefined;
state.fetched.value = false;
await actions.fetch();
},
}
appEventSource?.addEventListener("update", (event) => {
if (event.data.type !== "user-update") {
return;
}
console.log("appyling", event.data)
const zone = Info.normalizeZone(accountStore.activeTimezone);
const locale = accountStore.activeLocale;
state.users.value.apiUpdate({
type: "user",
entities: [event.data.data],
}, { zone, locale });
});
return {
...state,
...getters,
...actions,
};
})