59 lines
1.8 KiB
TypeScript
59 lines
1.8 KiB
TypeScript
import type { Topic } from "~~/types";
|
|
|
|
export const useTopics = async () => {
|
|
const appState = useAppState()
|
|
const fetchingTopics = ref(false);
|
|
const topics: Ref<any[] | null> = useState('topics', () => null);
|
|
|
|
/**
|
|
* Compute topics for the currently active agent
|
|
*/
|
|
const topicsForActiveAgent = computed(() => {
|
|
if (topics.value === null || !appState.activeAgentId.value) return [];
|
|
return topics.value.filter(topic => topic.agentId === appState.activeAgentId.value);
|
|
});
|
|
|
|
const activeTopic = computed(() => {
|
|
if (topicsForActiveAgent.value.length === 0) return;
|
|
if (!appState.activeTopicId.value) return;
|
|
|
|
const topic = topicsForActiveAgent.value.find(topic => topic.id === appState.activeTopicId.value);
|
|
return topic;
|
|
});
|
|
|
|
const refreshTopics = async () => {
|
|
if (fetchingTopics.value) return;
|
|
fetchingTopics.value = true;
|
|
|
|
try {
|
|
const { data, error } = await useFetch('/api/topics');
|
|
if (error.value) throw error;
|
|
topics.value = data.value!;
|
|
} finally {
|
|
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')
|
|
}
|
|
|
|
const newTopic = await res.json()
|
|
if (topics.value === null) topics.value = []
|
|
topics.value.push(newTopic)
|
|
return newTopic
|
|
}
|
|
|
|
return { createTopic, activeTopic, topics, topicsForActiveAgent, fetchingTopics, refreshTopics }
|
|
} |