27 lines
1.2 KiB
TypeScript
27 lines
1.2 KiB
TypeScript
|
|
import { usePocketBase } from "@/pocketbase";
|
|
import { RecordModel, RecordSubscription } from "pocketbase";
|
|
import { Ref, computed, onMounted, ref } from "vue";
|
|
|
|
export const watchCollection = <T extends RecordModel = RecordModel>(collection: string, topic: string, callback: (data: RecordSubscription<T>) => void) => {
|
|
const pb = usePocketBase();
|
|
|
|
onMounted(async () => await pb.collection(collection).subscribe<T>(topic, callback));
|
|
};
|
|
|
|
export const useCollection = <T extends RecordModel = RecordModel>(collection: string) => {
|
|
const pb = usePocketBase();
|
|
const list = ref<T[]>([]) as Ref<T[]>;
|
|
|
|
watchCollection<T>(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<T>().catch(() => [] as T[]));
|
|
return computed(() => list.value);
|
|
} |