javafacebook-graph-apijava-8restfb

How to get the number of replies from a comment with RestFB


I need to get the comments with your replies for all nodes owned by authenticated users.

I have it in the following way with stream java 8:

private Stream<Comment> getCommentsByObjectAfterThan(final FacebookClient facebookClient, final String objectId, final Date startDate, User user) {

        Connection<Comment> commentConnection
                = facebookClient.fetchConnection(objectId + "/comments", Comment.class);

        return StreamUtils.asStream(commentConnection.iterator())
                .flatMap(List::stream)
                .flatMap(comment
                        -> StreamUtils.concat(
                        getCommentsByObjectAfterThan(facebookClient, comment.getId(), startDate, user), comment)
                )
                .filter(comment -> !comment.getFrom().getId().equals(user.getId()) &&
                        (startDate != null ? comment.getCreatedTime().after(startDate) : true));
    }

I need to optimize the second flapMap that creates a stream with the top-level comment and its replies.

Clearly it would have to do so:

.flatMap(comment ->  comment.getCommentCount() > 0 ? StreamUtils.concat(
             getCommentsByObjectAfterThan(facebookClient,comment.getId(), startDate, user), comment) : Stream.of(comment))

The problem is that it comment.getCommentCount() always returns 0 even though the comments have replies.

How can i fix this? Thanks in advance.


Solution

  • Change the line

    Connection<Comment> commentConnection
                = facebookClient.fetchConnection(objectId + "/comments", Comment.class);
    

    to

    Connection<Comment> commentConnection
                = facebookClient.fetchConnection(objectId + "/comments", Comment.class, Parameter.with("fields","comment_count");
    

    Then you get the comment_count field of the comment.