Created
September 16, 2022 14:40
-
-
Save reyco1/46417f5fce787ed4135b6ba315fa0831 to your computer and use it in GitHub Desktop.
Firebase Firestore Angular Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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