Skip to content

Instantly share code, notes, and snippets.

@reyco1
Created September 16, 2022 14:40
Show Gist options
  • Save reyco1/46417f5fce787ed4135b6ba315fa0831 to your computer and use it in GitHub Desktop.
Save reyco1/46417f5fce787ed4135b6ba315fa0831 to your computer and use it in GitHub Desktop.
Firebase Firestore Angular Service
import { Injectable } from '@angular/core';
import {
addDoc, collection, collectionData, CollectionReference,
deleteDoc, doc, docData, DocumentData, DocumentReference,
Firestore, query, QueryConstraint, setDoc, updateDoc
} from '@angular/fire/firestore';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DbService {
constructor(
private firestore: Firestore
) { }
// sample query constraint --> const wa:QueryConstraint[] = [where('dir','==','T'), where('day','==',23)]
queryCollection(collectionPath: string, queryConstriants: QueryConstraint[]): Observable<DocumentData[]> {
const collectionRef: CollectionReference<DocumentData> = collection(this.firestore, collectionPath);
const q = query(collectionRef, ...queryConstriants);
return collectionData(q, { idField: 'id' });
}
getCollection(collectionPath: string): Observable<DocumentData[]> {
const collectionRef: CollectionReference<DocumentData> = collection(this.firestore, collectionPath);
return collectionData(collectionRef, { idField: 'id' });
}
getDocument(collectionPath: string, id: string): Observable<DocumentData> {
const documentRef = doc(this.firestore, collectionPath, id);
return docData(documentRef, { idField: 'id' });
}
addDocument(collectionPath: string, data: DocumentData, id?: string): Promise<DocumentReference | void> {
const collectionRef: CollectionReference<DocumentData> = collection(this.firestore, collectionPath);
if (id) {
return setDoc(doc(collectionRef, id), data, { merge: true });
} else {
return addDoc(collectionRef, data);
}
}
deleteDocument(collectionPath: string, id: string): Promise<void> {
const documentRef = doc(this.firestore, collectionPath, id);
return deleteDoc(documentRef);
}
updateDocument(collectionPath: string, id: string, data: DocumentData): Promise<void> {
const documentRef = doc(this.firestore, collectionPath, id);
return updateDoc(documentRef, data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment