svelte-firebase-state
Version:
Simplify Firebase integration in Svelte and SvelteKit with reactive state management for Firestore and Realtime Database.
79 lines (78 loc) • 2.23 kB
JavaScript
import {} from "firebase/auth";
import { Firestore, QueryConstraint } from "firebase/firestore";
import { WritableState } from "../WritableState.svelte.js";
import { get_firebase_user } from "../utils.svelte.js";
export class FirestoreState {
auth;
firestore;
listen;
getUserPromise;
converter;
pathFunctionOrString;
dataState;
unsub;
initPromise;
loading = $state(false);
constructor({ auth, firestore, listen, fromFirestore, toFirestore, pathFunctionOrString, converter }) {
this.dataState = new WritableState(undefined, () => {
this.start();
return this.stop;
});
this.auth = auth;
this.firestore = firestore;
this.listen = listen ?? false;
this.pathFunctionOrString = pathFunctionOrString;
const defaultFromFirestore = (snap) => ({
...snap.data(),
id: snap.id
});
const defaultToFirestore = (data) => {
const { id, ...rest } = data;
return rest;
};
this.converter = converter ?? {
toFirestore: toFirestore ?? defaultToFirestore,
fromFirestore: fromFirestore ?? defaultFromFirestore
};
this.getUserPromise = get_firebase_user(this.auth);
this.initPromise = this.init();
}
get_path_string(user) {
if (typeof this.pathFunctionOrString === "function") {
return this.pathFunctionOrString(user) ?? null;
}
else if (typeof this.pathFunctionOrString === "string") {
return this.pathFunctionOrString;
}
return null;
}
async start() {
await this.initPromise;
if (this.listen) {
this.listen_data();
}
else {
this.fetch_data();
}
}
stop = () => {
if (this.unsub) {
this.unsub();
this.unsub = undefined;
}
};
get data() {
return this.dataState.value;
}
set data(data) {
this.dataState.value = data;
}
async fetch_data() { }
async init() {
return;
}
async listen_data() { }
refetch() {
return this.fetch_data();
}
}