|
| 1 | +import { |
| 2 | + collection, |
| 3 | + collectionData, |
| 4 | + CollectionReference, |
| 5 | + doc, |
| 6 | + docData, |
| 7 | + DocumentData, |
| 8 | + DocumentReference, |
| 9 | + Firestore, |
| 10 | + FirestoreDataConverter, |
| 11 | + Query, |
| 12 | +} from '@angular/fire/firestore'; |
| 13 | +import { Observable } from 'rxjs'; |
| 14 | + |
| 15 | +export interface FirestoreResourceConfig< |
| 16 | + ModelWithId extends DocumentData, |
| 17 | + Record extends DocumentData, |
| 18 | + IdField extends keyof ModelWithId, |
| 19 | +> { |
| 20 | + readonly path: string; |
| 21 | + readonly idField: IdField; |
| 22 | + readonly converter: FirestoreDataConverter< |
| 23 | + Omit<ModelWithId, IdField>, |
| 24 | + Record |
| 25 | + >; |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * A class that provides type-safe access to the Firestore collection and |
| 30 | + * documents of a specific model. |
| 31 | + */ |
| 32 | +export class FirestoreResource< |
| 33 | + ModelWithId extends DocumentData, |
| 34 | + Record extends DocumentData, |
| 35 | + IdField extends keyof ModelWithId, |
| 36 | +> { |
| 37 | + constructor( |
| 38 | + protected firestore: Firestore, |
| 39 | + protected config: FirestoreResourceConfig<ModelWithId, Record, IdField>, |
| 40 | + ) {} |
| 41 | + |
| 42 | + readonly path = this.config.path; |
| 43 | + readonly idField = this.config.idField; |
| 44 | + readonly converter = this.config.converter; |
| 45 | + |
| 46 | + refDoc(id: string): DocumentReference<Omit<ModelWithId, IdField>, Record> { |
| 47 | + const { path, converter } = this; |
| 48 | + return doc(this.firestore, path, id).withConverter(converter); |
| 49 | + } |
| 50 | + |
| 51 | + refNewDoc(): DocumentReference<Omit<ModelWithId, IdField>, Record> { |
| 52 | + const { converter } = this; |
| 53 | + const collectionRef = this.refCollection(); |
| 54 | + return doc(collectionRef).withConverter(converter); |
| 55 | + } |
| 56 | + |
| 57 | + refCollection(): CollectionReference<Omit<ModelWithId, IdField>, Record> { |
| 58 | + const { path, converter } = this; |
| 59 | + return collection(this.firestore, path).withConverter(converter); |
| 60 | + } |
| 61 | + |
| 62 | + resolveQuery( |
| 63 | + query: Query<Omit<ModelWithId, IdField>>, |
| 64 | + ): Observable<ModelWithId[]> { |
| 65 | + const { idField } = this; |
| 66 | + // Type-assert required because of the incorrect typing of the `idField` option |
| 67 | + return collectionData(query as Query<ModelWithId>, { idField }); |
| 68 | + } |
| 69 | + |
| 70 | + resolveDoc( |
| 71 | + ref: DocumentReference<Omit<ModelWithId, IdField>>, |
| 72 | + ): Observable<ModelWithId | undefined> { |
| 73 | + const { idField } = this; |
| 74 | + // Type-assert required because of the incorrect typing of the `idField` option |
| 75 | + return docData(ref as DocumentReference<ModelWithId>, { idField }); |
| 76 | + } |
| 77 | +} |
0 commit comments