UNPKG

svelte-firebase-state

Version:

Simplify Firebase integration in Svelte and SvelteKit with reactive state management for Firestore and Realtime Database.

54 lines (53 loc) 1.85 kB
import { getAggregateFromServer, collection, query as firestoreQuery, onSnapshot } from "firebase/firestore"; import { FirestoreState } from "./FirestoreState.svelte.js"; export class CollectionAggregateState extends FirestoreState { aggregate; queryRef; constructor({ auth, firestore, path: pathFunctionOrString, listen = false, aggregate }) { super({ auth, firestore, listen, pathFunctionOrString, fromFirestore: (data) => data, toFirestore: (data) => data }); this.aggregate = aggregate; } get_collection_from_path(path) { const pathArray = path.split("/"); return collection(this.firestore, ...pathArray); } async init() { const user = await this.getUserPromise; const pathStr = this.get_path_string(user); if (!pathStr) { throw new Error("Path string is not set"); } const collectionRef = this.get_collection_from_path(pathStr); this.queryRef = firestoreQuery(collectionRef); } async fetch_data() { this.loading = true; if (!this.queryRef) { throw new Error("Query reference is not set"); } const querySnapshot = await getAggregateFromServer(this.queryRef, this.aggregate); this.data = querySnapshot.data(); this.loading = false; } async listen_data() { if (this.unsub) { return; } if (!this.queryRef) { throw new Error("Query reference is not set"); } // Firestore does not support listening to aggregate queries // so we need to listen to the collection and re-fetch the data this.unsub = onSnapshot(this.queryRef, () => { this.fetch_data(); }); return; } }