Cloud Functions in Firebase: call parameter to be type Document Snapshot

Viewed 423

I am trying to use cloud functions to get a subcollection from a starting point. My cloud function is written in typescript and goes by:

export async function getCollection(path: any, start:any, orderBy: any) {
    return  admin
    .firestore()
    .collection(path)
    .orderBy(orderBy)
    .startAfter(start)
    .limit(10)
    .get()
    .then(snapshot => snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));
}

My code in Kotlin to call for the cloud function from my android app is:

fun getReleasedAnimalsData(startAfter: DocumentSnapshot):Task<ReleasedData>{
    /*val gsonObject = Gson().toJson(startAfter)
    val jsonObject = JSONObject(gsonObject)*/
    val data = hashMapOf("startAt" to startAfter)
    return functions
        .getHttpsCallable("function")
        .call(data)
        .continueWith { task ->
            val json = Gson().toJson(task.result?.data)
            val returnedData= Gson().fromJson(json,ReleasedData::class.java)
            returnedData
        }
}

When I try to do the calling, I get the following error:

Object cannot be encoded in JSON: DocumentSnapshot

I understand that Document Snapshot is a complex object and cant be serialized just like that but I cant seem to find the way to call the startAfter property from Firebase without a document snapshot.

You might be wondering: Why is he not making the call from the Android Firebase SDK? That is because this task I am trying to do is part of a bigger algorithm and I would prefer to only do one call to the instead of many calls from the android app. Is there a way to make this possible? Or should I just give up and use my Coroutines to do more than one async call?

Any help is appreciated! :)

1 Answers

If you can't pass a DocumentSnapshot object to startAfter, you can just pass the values of the fields that are used in the orderBy part of the query. See the API documentation for startAfter. It takes field values OR a document snapshot. And:

The order of the provided values must match the order of the order by clauses of the query.

So if you have a single orderBy on field X, then you can pass a single value for field X of the last document you saw.

Related