How do I query a user's friends' posts using QueryBuilder?

95 Views Asked by At

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?

1

There are 1 best solutions below

0
On

I haven't got the opportunity to test this, but it looks correct:

return user.$friends
    .query(on: request.db)
    .all()
    .flatMap { (friends: Array<User>) -> EventLoopFuture<Page<Post>> in
        return friends.map { friend in
            return Post
                .query(on: request.db)
                .filter(\.$user.$id == friend).all()
        }.flatten(on: request.eventLoop)
        .sort(\.$createdAt)
        .paginate(for: request)
    }

The queries return an array of arrays of Posts, so needs to be flattened before it is sorted and paginated.