|
| 1 | +import { writable } from "svelte/store"; |
| 2 | +import { onValue, ref as dbRef } from "firebase/database"; |
| 3 | +import type { Database } from "firebase/database"; |
| 4 | + |
| 5 | +/** |
| 6 | + * @param {Database} rtdb - Firebase Realtime Database instance. |
| 7 | + * @param {string} path - Path to the database reference. |
| 8 | + * @param {T | undefined} startWith - Optional default data. |
| 9 | + * @returns a store with realtime updates on individual database reference data. |
| 10 | + */ |
| 11 | +export function refStore<T = any>(rtdb: Database, path: string, startWith?: T) { |
| 12 | + const dataRef = dbRef(rtdb, path); |
| 13 | + |
| 14 | + const { subscribe } = writable<T | null>(startWith, (set) => { |
| 15 | + const unsubscribe = onValue(dataRef, (snapshot) => { |
| 16 | + set(snapshot.val() as T); |
| 17 | + }); |
| 18 | + |
| 19 | + return unsubscribe; |
| 20 | + }); |
| 21 | + |
| 22 | + return { |
| 23 | + subscribe, |
| 24 | + ref: dataRef, |
| 25 | + }; |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * @param {Database} rtdb - Firebase Realtime Database instance. |
| 30 | + * @param {string} path - Path to the database reference. |
| 31 | + * @param {T[]} startWith - Optional default data. |
| 32 | + * @returns a store with realtime updates on lists of data. |
| 33 | + */ |
| 34 | +export function listStore<T = any>( |
| 35 | + rtdb: Database, |
| 36 | + path: string, |
| 37 | + startWith: T[] = [] |
| 38 | +) { |
| 39 | + const listRef = dbRef(rtdb, path); |
| 40 | + |
| 41 | + const { subscribe } = writable<T[]>(startWith, (set) => { |
| 42 | + const unsubscribe = onValue(listRef, (snapshot) => { |
| 43 | + const dataArr: T[] = []; |
| 44 | + snapshot.forEach((childSnapshot) => { |
| 45 | + dataArr.push({ |
| 46 | + key: childSnapshot.ref.key, |
| 47 | + ...(childSnapshot.val() as T), |
| 48 | + }); |
| 49 | + }); |
| 50 | + set(dataArr); |
| 51 | + }); |
| 52 | + |
| 53 | + return unsubscribe; |
| 54 | + }); |
| 55 | + |
| 56 | + return { |
| 57 | + subscribe, |
| 58 | + ref: listRef, |
| 59 | + }; |
| 60 | +} |
0 commit comments