UNPKG

svelte-firebase-state

Version:

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

66 lines (65 loc) 2.17 kB
import {} from "firebase/auth"; import { ref, onValue, QueryConstraint, query, get, DataSnapshot, push, set } from "firebase/database"; import { RealtimeDatabaseState } from "./RealtimeDatabaseState.svelte.js"; export class NodeListState extends RealtimeDatabaseState { queryParamsFn; listRef; queryRef; constructor({ auth, database, path: pathFunctionOrString, listen = false, query: queryParamsFn }) { super({ auth, database, listen, pathFunctionOrString }); this.queryParamsFn = queryParamsFn; } async init_ref() { const pathStr = await this.get_path_string(); if (!pathStr) { throw new Error("Path is not defined"); } this.listRef = ref(this.database, pathStr); const user = await this.getUserPromise; const queryParams = this.queryParamsFn ? this.queryParamsFn(user) : []; this.queryRef = query(this.listRef, ...queryParams); } createArrayFromSnapshot(snapshot) { const arr = []; snapshot.forEach((childSnapshot) => { // const childKey = childSnapshot.key; const childData = childSnapshot.val(); arr.push(childData); }); return arr; } listen_data() { if (!this.queryRef) { throw new Error("queryRef is not set"); } this.unsub = onValue(this.queryRef, (snapshot) => { this.data = this.createArrayFromSnapshot(snapshot); }); } async fetch_data() { if (!this.queryRef) { throw new Error("Query reference is not set"); } const snapshot = await get(this.queryRef); this.data = this.createArrayFromSnapshot(snapshot); return this.data; } async get_list_ref() { await this.initRefPromise; return this.listRef; } async add(data) { await this.initRefPromise; if (!this.listRef) { throw new Error("listRef is not set"); } const newMessageRef = push(this.listRef); set(newMessageRef, data); return newMessageRef; } }