Created
January 3, 2019 23:22
-
-
Save mateusduraes/c9917c11584ddb596c1e5843b61d9073 to your computer and use it in GitHub Desktop.
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 { AngularFirestore, QueryFn } from '@angular/fire/firestore'; | |
import { Injectable } from '@angular/core'; | |
import { Observable } from 'rxjs-compat'; | |
import { map } from 'rxjs/operators'; | |
import * as firebase from 'firebase'; | |
@Injectable() | |
export class FirebaseService<T> { | |
constructor( | |
private afs: AngularFirestore, | |
) { } | |
public add(path: string, payload: T): Promise<firebase.firestore.DocumentReference> { | |
payload['createdAt'] = firebase.firestore.FieldValue.serverTimestamp() | |
return this.afs.collection(path).add(payload); | |
} | |
public get(path: string, queryFn?: QueryFn): Observable<T[]> { | |
const collection = this.afs.collection<any>(path, queryFn); | |
return collection.snapshotChanges().pipe( | |
map(actions => { | |
return actions.map(a => { | |
const data = a.payload.doc.data(); | |
const id = a.payload.doc.id; | |
return { id, ...data } as any; | |
}); | |
}), | |
); | |
} | |
public getDoc(path: string): Observable<T> { | |
const document = this.afs.doc(path); | |
return document.snapshotChanges().pipe( | |
map(action => { | |
const data = action.payload.data(); | |
const id = action.payload.id; | |
return { id, ...data } as any; | |
}), | |
); | |
} | |
public update(path: string, payload: T): Promise<void> { | |
const doc = this.afs.doc(path); | |
return doc.update(payload); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment