Store events that are to be broadcasted in the database, and fetch events to serve in the /api/event stream to the client from the database. This ensures that events are not lost if the operation to open the stream takes longer than usual, or the client was not connected at the time the event was broadcast. To ensure no events are lost in the transition from server generating the page to the client hydrating and establishing a connection with the event stream, the /api/last-event-id endpoint is first queried on the server before any other entities is fetched from the database. The client then passes this id when establishing the event stream, and receives all events greater than that id.
71 lines
1.8 KiB
TypeScript
71 lines
1.8 KiB
TypeScript
/*
|
|
SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
|
|
SPDX-License-Identifier: AGPL-3.0-or-later
|
|
*/
|
|
import { appendResponseHeader } from "h3";
|
|
import type { H3Event } from "h3";
|
|
import type { ApiAccount, ApiSession } from "~/shared/types/api";
|
|
|
|
const fetchSessionWithCookie = async (event?: H3Event) => {
|
|
// Client side
|
|
if (!event) {
|
|
return $fetch("/api/auth/session");
|
|
}
|
|
|
|
// Server side
|
|
const cookie = useRequestHeader("cookie");
|
|
const res = await $fetch.raw("/api/auth/session", {
|
|
headers: cookie ? { cookie } : undefined
|
|
});
|
|
for (const cookie of res.headers.getSetCookie()) {
|
|
appendResponseHeader(event, "set-cookie", cookie);
|
|
}
|
|
return res._data;
|
|
}
|
|
|
|
export const useSessionStore = defineStore("session", () => {
|
|
const state = {
|
|
account: ref<ApiAccount>(),
|
|
authenticationProvider: ref<string>(),
|
|
authenticationName: ref<string>(),
|
|
id: ref<number>(),
|
|
push: ref<boolean>(false),
|
|
};
|
|
|
|
const actions = {
|
|
async fetch(event?: H3Event) {
|
|
const session = await fetchSessionWithCookie(event)
|
|
actions.update(session);
|
|
},
|
|
update(session?: ApiSession) {
|
|
state.account.value = session?.account;
|
|
state.authenticationProvider.value = session?.authenticationProvider;
|
|
state.authenticationName.value = session?.authenticationName;
|
|
state.id.value = session?.id;
|
|
state.push.value = session?.push ?? false;
|
|
},
|
|
async logOut() {
|
|
try {
|
|
await $fetch.raw("/api/auth/session", {
|
|
method: "DELETE",
|
|
});
|
|
await actions.fetch();
|
|
|
|
} catch (err: any) {
|
|
alert(`Log out failed: ${err.statusCode} ${err.statusMessage}`);
|
|
}
|
|
},
|
|
};
|
|
|
|
appEventSource?.addEventListener("message", (event) => {
|
|
if (event.data.type !== "connected") {
|
|
return;
|
|
}
|
|
actions.update(event.data.session);
|
|
});
|
|
|
|
return {
|
|
...state,
|
|
...actions,
|
|
};
|
|
});
|