Use a pinia store to manage account state
All checks were successful
/ build (push) Successful in 3m29s
/ deploy (push) Successful in 47s

Refactor the existing scattered code dealing with the account state into
a pinia store.
This commit is contained in:
Hornwitser 2025-05-24 20:01:23 +02:00
parent fae8b4e2e4
commit e722876aae
12 changed files with 126 additions and 98 deletions

60
stores/account.ts Normal file
View file

@ -0,0 +1,60 @@
import type { Account } from "~/shared/types/account";
export const useAccountStore = defineStore("account", () => {
const runtimeConfig = useRuntimeConfig();
const sessionStore = useSessionStore();
const state = {
valid: ref<boolean>(false),
id: ref<number>(),
name: ref<string>(),
timezone: ref<string>(),
type: ref<Account["type"]>(),
interestedIds: ref<Set<string>>(),
};
watchEffect(() => {
const account = sessionStore.account;
state.valid.value = Boolean(account);
state.id.value = account?.id;
state.name.value = account?.name;
state.timezone.value = account?.timezone;
state.type.value = account?.type;
state.interestedIds.value = account?.interestedIds ? new Set(account.interestedIds) : undefined;
});
const getters = {
isCrew: computed(() => state.type.value === "crew" || state.type.value === "admin"),
canEdit: computed(() => state.type.value === "admin" || state.type.value === "crew" ),
canEditPublic: computed(() => state.type.value === "admin"),
activeTimezone: computed(() => state.timezone.value || runtimeConfig.public.defaultTimezone),
defaultTimezone: computed(() => runtimeConfig.public.defaultTimezone),
};
const actions = {
async toggleInterestedId(id: string, slotIds?: string[]) {
if (!state.interestedIds.value) {
throw Error("accountStore.toggleInterestedId: Invalid state")
}
let newIds = [...state.interestedIds.value ?? []];
if (state.interestedIds.value.has(id)) {
newIds = newIds.filter(newId => newId !== id);
} else {
newIds.push(id);
if (slotIds) {
const filterIds = new Set(slotIds);
newIds = newIds.filter(newId => !filterIds.has(newId));
}
}
await $fetch("/api/account", {
method: "PATCH",
body: { interestedIds: newIds },
})
await sessionStore.fetch();
},
};
return {
...state,
...getters,
...actions,
};
});