UNPKG

svelte-pocketbase-sync

Version:

A reactive wrapper for PocketBase collections and records in SvelteKit, allowing automatic updates and reactivity.

68 lines (67 loc) 2.72 kB
import { createSubscriber } from 'svelte/reactivity'; import { pb } from './pocketbase.svelte.js'; export class CollectionList { subscribe; localRecords = []; collection; //prettier-ignore /** * Creates a new reactive collection. * * @param {CollectionSubscriberOptions<T>} options - The configuration options for the collection. */ constructor({ name, onUpdate, onDelete, onCreate, onInit, insertOnUpdate }) { if (!name) throw new Error('Collection name is required'); this.collection = pb.collection(name); this.subscribe = createSubscriber((update) => { let off; const register = async () => { try { if (onInit) { this.localRecords = await onInit(this.collection) || []; update(); } off = await this.collection.subscribe('*', async ({ action, record }) => { if (action === 'update') { const localRecord = this.localRecords.find((r) => r.id === record.id); const customUpdate = onUpdate ? await onUpdate(record) : undefined; if (customUpdate) record = customUpdate; if (localRecord) Object.assign(localRecord, record); else if (insertOnUpdate) this.localRecords.push(record); } else if (action === 'create') { const customCreate = onCreate ? await onCreate(record) : undefined; if (customCreate) record = customCreate; this.localRecords.push(record); } else if (action === 'delete') { if (onDelete) await onDelete(record); this.localRecords = this.localRecords.filter((r) => r.id !== record.id); } update(); }); } catch (error) { console.error(`Error subscribing to collection: ${name}`, error); } }; register(); return () => off(); }); } /** * Gets the records stored in the collection. * * @returns {T[]} The list of records. */ get records() { this.subscribe(); return this.localRecords; } }