Search code examples
c#firebasegoogle-cloud-firestorefirebase-admin

How to apply unknown query operators to a collection reference on Firebase Client


I have written a GetCollectionAsync method for querying collections on Firestore. As long as I want to get the whole collection documents, it works fine. Now I want to introduce query operators such as: WhereEqualTo, WhereIn, WhereGreaterThanOrEqualTo, etc

I want my method to stay generic and expose a parameter so that the caller can pass one or many query operators. Is there a way to achieve this?

    public async Task<IEnumerable<T>> GetCollectionAsync<T>(string path, /* query operators? */) 
    {
        var collectionRef = _firestoreDb.Collection(path);

        /* apply query operators to collection reference? */

        var snapshot = await collectionRef.GetSnapshotAsync();
        return snapshot.ConvertTo<T>();
    } 

Solution

  • As requested by @FaridShumbar here's my workaround.

    The concession I made was to split the method in two. So the caller needs first to call a GetCollectionReference method, apply the filters on it, and pass it to QueryCollectionAsync to execute the query.

    Code below:

        public CollectionReference GetCollectionReference(string collectionPath)
        {
            return _firestoreDb.Collection(collectionPath);
        }
    
        public async Task<IEnumerable<T>> QueryCollectionAsync<T>(Query collectionReference)
        {
            var snapshot = await collectionReference.GetSnapshotAsync();
            return snapshot.ConvertTo<T>();
        }
    
        // Call example
        var collectionRef = _firebaseService.GetCollectionReference(path).WhereEqualTo("image", null);
        var articles = await _firebaseService.QueryCollectionAsync<MyArticle>(collectionRef);