Files
2025-05-06 14:37:07 +02:00

101 lines
2.8 KiB
TypeScript

import { defineStore } from "pinia";
import { subscribe } from "~/netcode";
import { GameResponseDTO } from "~/netcode/events/dto/gameresponse.dto";
import type { ConceptEvent } from "~/netcode/events/events";
import { handlers } from "~/netcode/handlers/game.handler";
export const useGameStore = defineStore("game", {
state: () => ({
game: {} as GameResponseDTO,
currentWord: null as null | string,
eventSource: null as null | EventSource,
}),
actions: {
subscribe(id: number) {
this.eventSource = subscribe(`/games/${id}/subscribe`);
this.eventSource.addEventListener("message", (message) => {
const data = JSON.parse(message.data as string) as ConceptEvent;
const type = data.type;
console.log(type);
if (type in handlers) {
handlers[type as keyof typeof handlers](data);
}
});
},
close() {
this.eventSource?.close();
},
async fetchGame(id: number) {
const config = useRuntimeConfig();
const data = await useFetch<GameResponseDTO>(
config.public.endpoint + `/games/` + id,
{
credentials: "include",
immediate: true,
},
);
if (data.data.value) {
this.game = data.data.value;
}
return data.data;
},
async joinGame(id: number) {
const config = useRuntimeConfig();
const data = await $fetch<GameResponseDTO>(
config.public.endpoint + `/games/` + id + "/join",
{
method: "POST",
credentials: "include",
},
);
},
async startGame(id: number) {
const config = useRuntimeConfig();
const data = await $fetch<GameResponseDTO>(
config.public.endpoint + `/games/` + id + "/start",
{
method: "POST",
credentials: "include",
},
);
},
async deleteGame(id: number) {
const config = useRuntimeConfig();
const data = await $fetch<GameResponseDTO>(
config.public.endpoint + `/games/` + id,
{
method: "DELETE",
credentials: "include",
},
);
},
async getCurrentWord(id: number) {
const config = useRuntimeConfig();
const data = await $fetch<string>(
config.public.endpoint + `/games/` + id + "/currentWord",
{
credentials: "include",
},
);
if (data) {
this.currentWord = data;
}
return data;
},
async sendMessage(id: number, message: string) {
const config = useRuntimeConfig();
const data = await $fetch<string>(
config.public.endpoint + `/games/` + id + "/message",
{
method: "POST",
body: {
value: message,
},
credentials: "include",
},
);
},
},
});