Use a pinia store to manage session state

Replace the convoluted useAccountSession composable with a pinia store
that in addition allows for the consolidation of all session related
functions to grouped into one module.
This commit is contained in:
Hornwitser 2025-05-24 17:53:33 +02:00
parent c47452a8b4
commit fae8b4e2e4
21 changed files with 181 additions and 118 deletions

View file

@ -4,7 +4,7 @@ let source: EventSource | null = null;
let sourceRefs = 0;
let sourceSessionId: number | undefined = undefined;
export const useSchedule = () => {
const { data: session } = useAccountSession();
const sessionStore = useSessionStore();
const requestFetch = useRequestFetch();
const asyncData = useAsyncData<Schedule>(
'schedule',
@ -14,8 +14,8 @@ export const useSchedule = () => {
const { data: schedule } = asyncData;
function connect() {
console.log("Opening event source sid:", session.value?.id);
sourceSessionId = session.value?.id;
console.log("Opening event source sid:", sessionStore.id);
sourceSessionId = sessionStore.id;
source = new EventSource("/api/events");
source.addEventListener("message", (message) => {
console.log("Message", message.data);
@ -43,11 +43,11 @@ export const useSchedule = () => {
connect();
})
watch(() => session.value?.id, () => {
if (sourceSessionId === session.value?.id) {
watch(() => sessionStore.id, () => {
if (sourceSessionId === sessionStore.id) {
return;
}
sourceSessionId = session.value?.id;
sourceSessionId = sessionStore.id;
console.log("Session changed, refetching schedule")
$fetch("/api/schedule").then(
data => { schedule.value = data; },

View file

@ -1,34 +0,0 @@
import { appendResponseHeader } from "h3";
import type { H3Event } from "h3";
const fetchWithCookie = async (url: string, event?: H3Event) => {
if (!event) {
return $fetch(url);
}
const cookie = useRequestHeader("cookie");
const res = await $fetch.raw(url, {
headers: cookie ? { cookie } : undefined
});
for (const cookie of res.headers.getSetCookie()) {
appendResponseHeader(event, "set-cookie", cookie);
}
return res._data;
}
export const useAccountSession = () => {
const event = useRequestEvent();
return useAsyncData(
"session",
async () => await fetchWithCookie("/api/auth/session", event),
{
transform: (input) => input === undefined ? false as any as null: input,
getCachedData(key, nuxtApp, context) {
if (context.cause === "refresh:manual")
return undefined
return nuxtApp.payload.data[key];
},
dedupe: "defer",
}
);
}