Files
webapp-front/store/lobby.store.ts
T
2025-05-06 14:37:07 +02:00

57 lines
1.6 KiB
TypeScript

import { defineStore } from "pinia";
import { subscribe } from "~/netcode";
import type { GameResponseDTO } from "~/netcode/events/dto/gameresponse.dto";
import type { ConceptEvent } from "~/netcode/events/events";
import { handlers } from "~/netcode/handlers/lobby.handler";
export const useLobbyStore = defineStore("lobby", {
state: () => ({
games: {} as Record<number, GameResponseDTO>,
eventSource: null as null | EventSource,
}),
actions: {
subscribe() {
this.eventSource = subscribe(`/games/subscribe`);
this.eventSource.addEventListener("message", (message) => {
const data = JSON.parse(message.data as string) as ConceptEvent;
const type = data.type;
if (type in handlers) {
handlers[type as keyof typeof handlers](data);
}
});
},
close() {
this.eventSource?.close();
},
async fetchGames() {
const config = useRuntimeConfig();
const data = await useFetch<GameResponseDTO[]>(
config.public.endpoint + `/games/`,
{
credentials: "include",
immediate: true,
},
);
if (data.data.value) {
for (const game of data.data.value) {
this.games[game.id] = game;
}
}
return data.data;
},
async createGame() {
const config = useRuntimeConfig();
const data = await $fetch<GameResponseDTO>(
config.public.endpoint + "/games",
{
method: "POST",
credentials: "include",
},
);
// this.games[data.id] = data;
return data;
},
},
});