I am using firebase firestore as my database and i have written firebase functions to retrieve data from the firestore database.
What i am trying to achieve is pagination and as per the docs i have implemented the code for my firebase function. Below is the code:
exports.getBillList = functions.https.onRequest((req, res) => {
let docs=[];
let limit = 15;
return cors(req, res, () => {
let lastBillInList=req.query.lastBillInList;
console.log("lastBillInList value: " + lastBillInList);
if (lastBillInList === null || lastBillInList === undefined) lastBillInList = 0;
//var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];
if(lastBillInList==0){
console.log('first time call: as no lastbillseqq');
db.collection("bills").orderBy('billNo','desc').limit(limit).get().then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
docs.push(doc.data());
});
res.status(200).send(docs);
}).catch(function (error) {
console.error("Error getting list: ", error);
res.status(500).send();
});
}else{
console.log('second time call: as no lastbillseqq'+ lastBillInList);
db.collection("bills").orderBy('billNo', 'desc').startAfter(lastBillInList).limit(limit).get().then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
docs.push(doc.data());
});
res.status(200).send(docs);
}).catch(function (error) {
console.error("Error getting list: ", error);
res.status(500).send();
});
}
});
});
I have added condition to my firebase function where it checks whether a last bill number is provided.
If yes then retrieve all bill records after the last bill till the set limit or else if no last bill number is provided then consider it as first request and retrieve the initial records upto the limit
However the problem I am facing is that irrespective of code executing the else part, when the last bill number is provided , the query always return the records from the start of the result upto the limit specified. For some reason StartAfter is not working
e.g i have records with bill number form 1 to 25 , i have arranged them in descending order in above code ,so the result is from bill number 25 to 1.
When no bill number is provided i get result of bill numbers from 25 to 11. When I provide the bill number i get result from bill numbers 25 to 11 instead of expected bill numbers from 10 to 1.
Can anyone help me out in this?
Ok, I've found an interesting point. You have to call
start(afterDocument:)
beforelimit(to:)
otherwise it won't working as expected. So it should be something like following:I could manage to paginate by below code. In my model object I have used the Document ID , based on which i find the documentReference -> documentSnapshot. I finally use the documentSnapshot to compare(this was my mistake as earlier i was not using documentSnapshot) to get the desired output.
Below is my code: