Files
veridian/app/composables/useTopics.ts
T
2026-01-11 05:04:29 -06:00

49 lines
1.3 KiB
TypeScript

import type { Topic } from "~~/types";
export const useTopics = async () => {
const fetchingTopics = ref(false);
const topics: Ref<Topic[] | null> = useState('topics', () => null);
const activeTopic = computed(() => {
if (topics.value === null) return;
const routeId = useRoute().query.topicId;
if (routeId === undefined) return;
const topic = topics.value.find(topic => topic.id === routeId);
if (topic === undefined) return;
return topic;
});
const refreshTopics = async () => {
if (fetchingTopics.value) return;
fetchingTopics.value = true;
const { data, error } = await useFetch('/api/topics');
if (error.value) throw error;
topics.value = data.value!;
fetchingTopics.value = false;
}
if (topics.value === null) await refreshTopics();
const createTopic = async (name: string, agentId: string) => {
const res = await fetch('/api/topics', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name, agentId })
})
if (!res.ok) {
throw new Error('Failed to create topic')
}
return res.json()
}
return { createTopic, activeTopic, topics }
}