import { defineStore } from "pinia"; import { subscribe } from "~/netcode"; import { WordResponseDTO } from "~/netcode/events/dto/wordresponse.dto"; import { handlers } from "~/netcode/handlers/word.handler"; export const useWordStore = defineStore("word", { state: () => ({ words: {} as Record, eventSource: null as null | EventSource, }), actions: { async subscribe() { this.eventSource = subscribe(`/words/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 fetchWordList() { const config = useRuntimeConfig(); const data = await useFetch( config.public.endpoint + `/words/all`, { credentials: "include", } ); if (data.data.value && !data.error.value) { for (const word of data.data.value) { this.words[word.id] = word; } } return data; }, async enableWord(word: WordResponseDTO) { const config = useRuntimeConfig(); const data = await $fetch( config.public.endpoint + `/words/` + word.id + "/enable", { credentials: "include", method: "PUT", } ); word.enabled = true; return data; }, async disableWord(word: WordResponseDTO) { const config = useRuntimeConfig(); const data = await $fetch( config.public.endpoint + `/words/` + word.id + "/disable", { credentials: "include", method: "PUT", } ); word.enabled = false; return data; }, async createWord(value: string) { const config = useRuntimeConfig(); const data = await $fetch( config.public.endpoint + `/words/`, { credentials: "include", body: { value }, method: "POST", } ); this.words[data.id] = data; return data; }, async deleteWord(word: WordResponseDTO) { const config = useRuntimeConfig(); const data = await $fetch( config.public.endpoint + `/words/` + word.id, { credentials: "include", method: "DELETE", } ); delete this.words[word.id]; }, }, });