I have this method in a Angular project:
getData(collection: string, field: string, operator: WhereFilterOp, value: string) {
return new Promise<any>((resolve, reject) => {
this.afs.collection(collection, ref => ref.where(field, operator, value)).snapshotChanges().subscribe(snapshots => {
resolve(snapshots);
})
})
}
It works fine, but I have points in my system that I need more operators in my queries, how I really don't like to write code I want to pass a array of operators for a single method that resolve any query I wish to create a method like this:
getData(collection: string, query: FirestoreQuery[], value: string) {
return new Promise<any>((resolve, reject) => {
this.afs.collection(collection, ref =>
query.forEach(x => {
ref.where(x.field, x.operator, x.value);
})
).snapshotChanges().subscribe(snapshots => {
resolve(snapshots);
})
})
}
I created a model to tipify the array of operators:
import { WhereFilterOp } from "@firebase/firestore-types";
export class FirestoreQuery {
field: string;
operator: WhereFilterOp;
value: string;
}
Anybody can help to create this method or show me other way to pass a array of operators for a single getData method for my system. Write code is boring. I need get focused in my solution.
AskFirebase
You can use a reducer function to combine the queries.
import { WhereFilterOp } from '@firebase/firestore-types';
getData(collectionName: string, ...queries: any[]): Observable<any> {
const collection = this.db.collection(collectionName, ref => {
return queries.reduce((accumulator, query) => {
const [fieldPath, opString, value] = query;
return accumulator.where(fieldPath, opString as WhereFilterOp, value);
}, ref);
});
return collection.snapshotChanges();
}
// Usage
getData('sampleCollection', ['foo', '>', 0], ['foo', '<', 10]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With