Skip to content

Instantly share code, notes, and snippets.

@fariasmateuss
Forked from evlymn/firestore.service.ts
Created December 15, 2022 20:39
Show Gist options
  • Save fariasmateuss/be9f41acb1ffd6aa5fe4f5e544ae8565 to your computer and use it in GitHub Desktop.
Save fariasmateuss/be9f41acb1ffd6aa5fe4f5e544ae8565 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