I have created an public restful POST api for searching using Firebase function and firestore:
app.post("/", async (req, res) => {
const { eventIds, queryString, startAtIndex, limit } = req.body;
let query = firestore()
.collection("IndexedEcImage_test")
.where("eventId", 'in', eventIds);
if (queryString) {
query = query.where("generatedSearchKeys", "array-contains", queryString);
}
query = query.orderBy("timestamp")
if (startAtIndex) {
query = query.startAfter(startAtIndex);
}
const snapshot = await query.limit(limit).get();
const results = snapshot.docs.map(doc => doc.data());
res.status(200).send({
indexForNextPage: results[results.length - 1].timestamp,
data: results
});
});
The body request:
{
"eventIds": [
"9m6k89aOlqeXpaJ3oZhW1"
],
"queryString": "ABC",
"startAtIndex": 1637128385472,
"limit": 2
}
The output is like this: { "indexForNextPage": 1637128385472, "data": [{...},{....}] }
For example: The "IndexedEcImage_test" collection has 5 docs. I expected that the pagination would be like that:
Page 1: first 2 docs => Page 2: next 2 docs => Last page: the last doc
The indexForNextPage in the output is used to fetch the next page, but when it comes to the last page, it gave me a timeout. I guess the limit goes beyond the number of the remaining docs. The number of remaining docs can change differently depending on the total docs or the limit. Is there a general way to fetch the last page without counting all the docs?