Skip to content

Instantly share code, notes, and snippets.

@evlymn
Last active August 29, 2023 19:29
Show Gist options
  • Save evlymn/3369172043d18609fca4e5d426dc1cd7 to your computer and use it in GitHub Desktop.
Save evlymn/3369172043d18609fca4e5d426dc1cd7 to your computer and use it in GitHub Desktop.
Firestore Basics, Modular Firebase 9
import { Injectable } from '@angular/core';
import { Firestore, collectionData, collection, QueryConstraint } from '@angular/fire/firestore';
import { addDoc, CollectionReference, deleteDoc, doc, getDoc, query, setDoc, updateDoc } from '@firebase/firestore';
import { enableIndexedDbPersistence } from 'firebase/firestore';
@Injectable({
providedIn: 'root'
})
export class FirestoreService {
constructor(private firestore: Firestore) {
this.enableIndexedDbPersistence();
}
createId() {
return doc(collection(this.firestore, 'id')).id;
}
enableIndexedDbPersistence() {
enableIndexedDbPersistence(this.firestore)
}
list<T>(path: string, ...q: QueryConstraint[]) {
return collectionData<T>(
query<T>(
collection(this.firestore, path) as CollectionReference<T>,
...q
), { idField: 'id' }
);
}
add(path: string, data: any) {
const ref = collection(this.firestore, path);
return addDoc(ref, this.setUndefinedValuesToNull(data));
}
set(path: string, data: any) {
const ref = doc(this.firestore, path);
return setDoc(ref, this.setUndefinedValuesToNull(data));
}
get(path: string) {
const ref = doc(this.firestore, path);
return getDoc(ref);
}
update(path: string, data: any) {
const ref = doc(this.firestore, path);
return updateDoc(ref, this.setUndefinedValuesToNull(data));
}
delete(path: string) {
const ref = doc(this.firestore, path);
return deleteDoc(ref);
}
setUndefinedValuesToNull(data: any) {
Object.keys(data).filter(k => data[k] == undefined).forEach(k => data[k] = null);
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment