Firestore pagination backward and forward

Viewed 159

The cost of document read in my app is going really high. I'm trying to optimize document reads.

enum FetchDirection {
    // Last record date
    case old(date: Date, limit: Int)

    // First record date
    case new(date: Date, limit: Int)

    case initial(limit: Int)
}

func fetchPastWinners(fetchDirection: FetchDirection) -> SignalProducer<[Contest], FetchError> {
    switch fetchDirection {
    case .initial(let limit):
        return Firestore.firestore()
            .collection(Contest.collectionName)
            .limit(to: limit)
            .whereField(Contest.Key.isLive.rawValue, isEqualTo: false)
            .order(by: Contest.Key.endDate.rawValue, descending: true)
            .getDocuments()

    case .old(let date, let limit):
        return Firestore.firestore()
            .collection(Contest.collectionName)
            .limit(to: limit)
            .whereField(Contest.Key.isLive.rawValue, isEqualTo: false)
            .order(by: Contest.Key.endDate.rawValue, descending: true)
            .start(at: [date])
            .getDocuments()
            
    case .new(let date, let limit):
        return Firestore.firestore()
            .collection(Contest.collectionName)
            .limit(to: limit)
            .whereField(Contest.Key.isLive.rawValue, isEqualTo: false)
            .order(by: Contest.Key.endDate.rawValue, descending: true)
            .end(at: [date])
            .getDocuments()
    }
}
  • .initial loads an initial 25 records
  • .old loads past records when user scrolls to the bottom
  • .new tries to load new data since last fetch (expected to return empty if there is no new data)

The problem is with new. It always returns at least 1 record which is the top record so it creates duplicate record on each refresh instead of returning no result when there is no new data

I have tried the following and both return the first record if there is no new data

.end(at: [date])
.end(before: [date])
0 Answers
Related