My goal is to incorporate the Repository Pattern using Firestore Firebase and TypeScript.
Here is the code snippet:
import { firestore } from "firebase-admin";
import { ISearchCriteria } from './ISearchCriteria'
export class DBContext {
static current: DBContext = new DBContext();
private db: firestore.Firestore;
private constructor() {
this.db = firestore();
}
collection(collectionName: string): firestore.CollectionReference<firestore.DocumentData> {
return this.db.collection(collectionName);
}
public async where<T extends object>(collectionName: string, searchCriteria: ISearchCriteria[]): Promise<T[]> {
var snapShot = this.collection(collectionName);
for (var i = 0; i < searchCriteria.length; i++) {
snapShot = snapShot.where(searchCriteria[i].fieldName, searchCriteria[i].filterOp, searchCriteria[i].value);
}
let res = await snapShot.get();
return res.docs.map<T>(doc => ({ id: doc.id, ...doc.data() }) as T);
}
async get<T extends object>(collectionName: string): Promise<T[]> {
let res = await this.collection(collectionName).get();
return res.docs.map<T>(doc => ({ id: doc.id, ...doc.data() } as T));
}
async create<T extends object>(collectionName: string, item: T): Promise<T> {
return (await this.collection(collectionName).add(item)) as T;
}
async update<T extends object>(collectionName: string, id: string, item: T): Promise<firestore.WriteResult> {
var docRef = this.collection(collectionName).doc(id);
return await docRef.update(item);
}
async delete<T extends object>(collectionName: string, id: string): Promise<firestore.WriteResult> {
return await this.collection(collectionName).doc(id).delete();
}
}
I tried following an example provided in this link.
However, I encountered the following error message:
dbcontext.ts:23:13 - error TS2740: Type 'Query<DocumentData>' is missing the following properties from type 'CollectionReference<DocumentData>': id, parent, path, listDocuments, and 2 more.
The error occurs at this specific line:
snapShot = snapShot.where(searchCriteria[i].fieldName, searchCriteria[i].filterOp, searchCriteria[i].value);
This is the structure of ISearchCriteria:
import { firestore } from "firebase-admin";
export interface ISearchCriteria {
fieldName: string | firestore.FieldPath,
filterOp: FirebaseFirestore.WhereFilterOp,
value: any
}