I want to query all user's friends' posts from the database. I've worked out the following code, which seems to work but doesn't look that good, especially the part where I filter for the posts that have the user ids.
user.$friends
.query(on: request.db)
.all()
.flatMap { (friends: Array<User>) -> EventLoopFuture<Page<Post>> in
return Post
.query(on: request.db)
.filter(\.$user.$id ~~ friends.reduce(into: [], { (ids: inout Set<UUID>, user: User) in
if let id: UUID = user.id {
ids.insert(id)
}
}))
.sort(\.$createdAt)
.paginate(for: request)
}
How can I clean this code up?
I haven't got the opportunity to test this, but it looks correct:
The queries return an array of arrays of Posts, so needs to be flattened before it is sorted and paginated.