I am using Swift 5 and Vapor 3. I have written a client to call Twitter to get followers of a user. It looks like this
func followersOf(_ screenName : String, nextCursor : Int64 = -1) throws -> Future<UserCursor> {
logger.debug("Fetching followers of \(screenName)")
let res = httpClient.get("https://api.twitter.com/1.1/followers/list.json?screen_name=\(screenName)&nextCursor=\(nextCursor)", headers: ["authorization": authToken])
return res.flatMap { res in
return try res.content.decode(UserCursor.self, using: self.jsonDecoder)
}
}
UserCursor returns a value for the nextCursor and a list of Users for for the page that was fetched. I need to keep calling this method with the value of nextCursor and accumulating the Users for each page until nextCursor returns -1. How would I use the Future returned from this method to iteratively call it until I have visited all the pages of the cursor while accumulating the Users returned from each call?
This is what I have so far but I'm at a loss. I feel I'm way off the mark.
func followersOf(_ req : Request) throws -> Future<FollowersView> {
let logger = try req.make(Logger.self)
let screenName = try req.parameters.next(String.self)
logger.debug("Request for followers of \(screenName)")
let twitter = try req.make(TwitterClient.self)
return try twitter.followersOf(screenName).flatMap { userCursor in
var uc = userCursor
var users : Set<User> = []
users = users.union(userCursor.users)
while (uc.nextCursor != -1) {
try twitter.followersOf(screenName, nextCursor: userCursor.nextCursor).map { uc in uc}
}
return FollowersView(screenName, users)
}
}