UNPKG

svelte-pocketbase-sync

Version:

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

65 lines (64 loc) 2.45 kB
import { createSubscriber } from 'svelte/reactivity'; import { pb } from './pocketbase.svelte.js'; export class CollectionRecord { subscribe; localRecord; collection; //prettier-ignore /** * Creates a new reactive collection. * * @param {CollectionSubscriberOptions<T>} options - The configuration options for the collection. */ constructor({ name, onUpdate, onDelete, onCreate, onInit, recordId }) { 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.localRecord = await onInit(this.collection); update(); } off = await this.collection.subscribe(recordId, async ({ action, record }) => { if (action === 'update') { const customUpdate = onUpdate ? await onUpdate(record) : undefined; if (customUpdate) record = customUpdate; if (this.localRecord) Object.assign(this.localRecord, record); } else if (action === 'create') { const customCreate = onCreate ? await onCreate(record) : undefined; if (customCreate) record = customCreate; this.localRecord = record; } else if (action === 'delete') { if (onDelete) await onDelete(record); this.localRecord = undefined; } update(); }); } catch (error) { console.error(`Error subscribing to collection: ${name}`, error); } }; register(); return () => off(); }); } /** * Gets the record stored in the collection. * * @returns {T} The list of records. */ get record() { this.subscribe(); return this.localRecord; } }