import { defineStore } from "pinia"; import { subscribe } from "~/netcode"; import type { ConceptResponseDTO, ConceptTypeResponseDTO, } from "~/netcode/events/dto/conceptresponse.dto"; import type { ConceptEvent } from "~/netcode/events/events"; import { handlers } from "~/netcode/handlers/concept.handler"; export const useConceptStore = defineStore("concept", { state: () => ({ concepts: {} as Record, eventSource: null as null | EventSource, conceptTypes: {} as Record, }), actions: { subscribe() { this.eventSource = subscribe(`/concepts/subscribe`); this.eventSource.addEventListener("message", (message) => { const data = JSON.parse(message.data) as ConceptEvent; const type = data.type; if (type in handlers) { handlers[type as keyof typeof handlers](data); } }); }, close() { this.eventSource?.close(); }, async fetchConceptTypes() { const config = useRuntimeConfig(); const data = await useFetch( config.public.endpoint + `/concepts/types`, { credentials: "include", }, ); if (data.data.value && !data.error.value) { for (const conceptType of data.data.value) { this.conceptTypes[conceptType.id] = conceptType; } } return this.conceptTypes; }, async fetchConceptList() { const config = useRuntimeConfig(); const data = await useFetch( config.public.endpoint + `/concepts/all`, { credentials: "include", }, ); if (data.data.value && !data.error.value) { for (const concept of data.data.value) { this.concepts[concept.id] = concept; } } return data; }, async enableConcept(concepts: ConceptResponseDTO) { const config = useRuntimeConfig(); const data = await $fetch( config.public.endpoint + `/concepts/` + concepts.id + "/enable", { credentials: "include", method: "PUT", }, ); // word.enabled = true; // return data; }, async disableConcept(concepts: ConceptResponseDTO) { const config = useRuntimeConfig(); const data = await $fetch( config.public.endpoint + `/concepts/` + concepts.id + "/disable", { credentials: "include", method: "PUT", }, ); // word.enabled = false; // return data; }, async createConcept(value: string) { const config = useRuntimeConfig(); const data = await $fetch( config.public.endpoint + `/concepts/`, { credentials: "include", body: { value }, method: "POST", }, ); }, async deleteConcept(id: number) { const config = useRuntimeConfig(); const data = await $fetch( config.public.endpoint + `/concepts/` + id, { credentials: "include", method: "DELETE", }, ); }, }, });