WIP: load more comments for a post

Signed-off-by: Vartan Benohanian <vartanbeno@gmail.com>
This commit is contained in:
Vartan Benohanian
2020-07-29 14:11:06 -04:00
parent 8541c81438
commit 112f7f0370
4 changed files with 115 additions and 41 deletions
+67
View File
@@ -2,6 +2,7 @@ package reddit
import (
"context"
"errors"
"net/http"
"net/url"
)
@@ -63,3 +64,69 @@ func (s *CommentService) Edit(ctx context.Context, id string, text string) (*Com
return root, resp, nil
}
// LoadMoreReplies retrieves more replies that were left out when initially fetching the comment.
func (s *CommentService) LoadMoreReplies(ctx context.Context, comment *Comment) (*Response, error) {
if comment == nil {
return nil, errors.New("comment: must not be nil")
}
if !comment.hasMore() {
return nil, nil
}
postID := comment.PostID
commentIDs := comment.Replies.MoreComments.Children
type query struct {
PostID string `url:"link_id"`
IDs []string `url:"children,comma"`
APIType string `url:"api_type"`
}
path := "api/morechildren"
path, err := addOptions(path, query{postID, commentIDs, "json"})
if err != nil {
return nil, err
}
req, err := s.client.NewRequest(http.MethodGet, path, nil)
if err != nil {
return nil, err
}
type rootResponse struct {
JSON struct {
Data struct {
Things Things `json:"things"`
} `json:"data"`
} `json:"json"`
}
root := new(rootResponse)
resp, err := s.client.Do(ctx, req, root)
if err != nil {
return resp, err
}
comments := root.JSON.Data.Things.Comments
for _, c := range comments {
addCommentToReplies(comment, c)
}
comment.Replies.MoreComments = nil
return resp, nil
}
// addCommentToReplies traverses the comment tree to find the one
// that the 2nd comment is replying to. It then adds it to its replies.
func addCommentToReplies(parent *Comment, comment *Comment) {
if parent.FullID == comment.ParentID {
parent.Replies.Comments = append(parent.Replies.Comments, comment)
return
}
for _, reply := range parent.Replies.Comments {
addCommentToReplies(reply, comment)
}
}