import { usePocketBase } from "@/pocketbase"; import { RecordModel, RecordSubscription } from "pocketbase"; import { Ref, computed, onMounted, ref } from "vue"; export const watchCollection = (collection: string, topic: string, callback: (data: RecordSubscription) => void) => { const pb = usePocketBase(); onMounted(async () => await pb.collection(collection).subscribe(topic, callback)); }; export const useCollection = (collection: string) => { const pb = usePocketBase(); const list = ref([]) as Ref; watchCollection(collection, '*', data => { if (data.action === 'delete') { list.value = list.value.filter(i => i.id !== data.record.id); } else if (data.action === 'update') { list.value = list.value.map(i => i.id === data.record.id ? data.record : i); } else if (data.action === 'create') { list.value = [...list.value, data.record]; } }); onMounted(async () => list.value = await pb.collection(collection).getFullList().catch(() => [] as T[])); return computed(() => list.value); }