Skip to content

Instantly share code, notes, and snippets.

@loiane
Forked from evlymn/firestore.service.ts
Created September 30, 2021 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loiane/7f2a5c0cc00ee8dad21b57a2e7f8fff5 to your computer and use it in GitHub Desktop.
Save loiane/7f2a5c0cc00ee8dad21b57a2e7f8fff5 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';
@Injectable({
providedIn: 'root'
})
export class FirestoreService {
constructor(private firestore: Firestore) { }
createId() {
return doc(collection(this.firestore, 'id')).id;
}
list<T>(path: string, idField: string | undefined, ...q: QueryConstraint[]) {
return collectionData<T>(
query<T>(
collection(this.firestore, path) as CollectionReference<T>,
...q
), { idField }
);
}
add(path: string, data: any) {
const ref = collection(this.firestore, path);
return addDoc(ref, data);
}
set(path: string, data: any) {
const ref = doc(this.firestore, path);
return setDoc(ref, 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, data);
}
delete(path: string) {
const ref = doc(this.firestore, path);
return deleteDoc(ref);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment