This commit is contained in:
2020-03-07 23:00:11 +01:00
committed by smuddy
parent ccd91aa81c
commit d68cd590ad
57 changed files with 2012 additions and 3489 deletions

View File

@@ -0,0 +1,12 @@
import {TestBed} from '@angular/core/testing';
import {DbService} from './db.service';
describe('DbService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: DbService = TestBed.get(DbService);
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,44 @@
import {Injectable} from '@angular/core';
import {AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument} from '@angular/fire/firestore';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
type CollectionPredicate<T> = string | AngularFirestoreCollection<T>;
type DocumentPredicate<T> = string | AngularFirestoreDocument<T>;
@Injectable({
providedIn: 'root'
})
export class DbService {
constructor(private afs: AngularFirestore) {
}
public col<T>(ref: CollectionPredicate<T>, queryFn?): AngularFirestoreCollection<T> {
return typeof ref === 'string' ? this.afs.collection<T>(ref, queryFn) : ref;
}
public doc<T>(ref: DocumentPredicate<T>): AngularFirestoreDocument<T> {
return typeof ref === 'string' ? this.afs.doc<T>(ref) : ref;
}
public doc$<T>(ref: DocumentPredicate<T>): Observable<T> {
return this.doc(ref).snapshotChanges().pipe(
map(doc => {
const data = doc.payload.data();
const id = doc.payload.id;
return {...data, id} as T;
})
);
}
public col$<T>(ref: CollectionPredicate<T>, queryFn?): Observable<T[]> {
return this.col(ref, queryFn).snapshotChanges().pipe(
map(doc => doc.map(_ => {
const data = _.payload.doc.data();
const id = _.payload.doc.id;
return {...data, id} as T;
}))
);
}
}

View File

@@ -3,19 +3,19 @@ import {AngularFireAuth} from '@angular/fire/auth';
import {Observable} from 'rxjs';
import {filter, switchMap} from 'rxjs/operators';
import {User} from './user';
import {AngularFirestore} from '@angular/fire/firestore';
import {DbService} from './db.service';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private afAuth: AngularFireAuth, private afs: AngularFirestore) {
constructor(private afAuth: AngularFireAuth, private db: DbService) {
}
public get user$(): Observable<User> {
return this.afAuth.authState.pipe(
filter(_ => !!_),
switchMap(auth => this.afs.doc<User>('user/' + auth.uid).valueChanges())
switchMap(auth => this.db.doc$<User>('user/' + auth.uid))
);
}
}

View File

@@ -1,4 +1,5 @@
export interface User {
id: string;
name: string;
role: 'admin';
}