56 lines
1.5 KiB
TypeScript
56 lines
1.5 KiB
TypeScript
import { defineStore } from "pinia";
|
|
import { subscribe } from "~/netcode";
|
|
import type { GameResponseDTO } from "~/netcode/events/dto/gameresponse.dto";
|
|
import { handlers } from "~/netcode/handlers/lobby.handler";
|
|
|
|
export const useLobbyStore = defineStore("lobby", {
|
|
state: () => ({
|
|
games: {} as Record<number, GameResponseDTO>,
|
|
eventSource: null as null | EventSource,
|
|
}),
|
|
actions: {
|
|
async subscribe() {
|
|
this.eventSource = subscribe(`/games/subscribe`);
|
|
this.eventSource.addEventListener("message", async (message) => {
|
|
const data = JSON.parse(message.data);
|
|
const type = data.type as string;
|
|
if (type in handlers) {
|
|
handlers[type as keyof typeof handlers](data);
|
|
}
|
|
});
|
|
},
|
|
async 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;
|
|
},
|
|
},
|
|
});
|