Skip to content

Instantly share code, notes, and snippets.

@Crypt0Graphic
Last active May 26, 2024 20:12
Show Gist options
  • Save Crypt0Graphic/9e86de918ace4b10081f82977eef6e43 to your computer and use it in GitHub Desktop.
Save Crypt0Graphic/9e86de918ace4b10081f82977eef6e43 to your computer and use it in GitHub Desktop.
Generic Firestore Service for Angular (Firebase SDK 10+)
// Tested in Angular 17+ with Firebase SDK 10+
import { Injectable, inject } from '@angular/core';
import { Firestore, QueryConstraint, collection, getDocs } from '@angular/fire/firestore';
import { CollectionReference, addDoc, deleteDoc, doc, getDoc, query, setDoc, updateDoc } from '@firebase/firestore';
import { Observable, from, map } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FirestoreService {
private firestore = inject(Firestore);
// Usage: this.firestoreService.list<*InterfaceName*>('*Collection*', *Queries Separated With Comma* );
list<T>(path: string, ...q: QueryConstraint[]): Observable<T[]> {
const collectionRef = collection(this.firestore, path) as CollectionReference<T>;
const qRef = query(collectionRef, ...q);
return from(getDocs(qRef)).pipe(
map(snapshot => snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() } as T)))
);
}
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), { merge: true });
}
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