Skip to content

Commit

Permalink
fix: Invalid result of Reddit query
Browse files Browse the repository at this point in the history
When Reddit cannot find query, it should return empty list.
  • Loading branch information
macie committed Dec 10, 2023
1 parent fb6abd8 commit d18f736
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
13 changes: 13 additions & 0 deletions reddit.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ type RedditResponse struct {
} `json:"data"`
}

// UnmarshalJSON deserialize inconsistent JSON responses to RedditResponse.
// Reddit returns empty object ("{}") when there are no search results.
func (r *RedditResponse) UnmarshalJSON(b []byte) error {
isEmptyResponse := len(b) == 4 && string(b) == "\"{}\""
if isEmptyResponse {
return nil
}

// new type prevents recursive calls to RedditResponse.UnmarshalJSON()
type resp *RedditResponse
return json.Unmarshal(b, resp(r))
}

// SearchReddit searches Reddit for given query and returns list of discussions
// sorted by relevance.
//
Expand Down
11 changes: 11 additions & 0 deletions reddit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,14 @@ func ExampleSearchReddit() {
// Output:
// Reddit https://reddit.com/r/hypeurls/comments/17k6i1l/the_grug_brained_developer_2022/ The Grug Brained Developer (2022) https://grugbrain.dev/
}

func ExampleSearchReddit_unknown() {
client := http.Client{}
query := "https://invalid.domain/query"

opinions := ensure.MustReturn(SearchReddit(context.TODO(), client, query))

fmt.Println(len(opinions))
// Output:
// 0
}

0 comments on commit d18f736

Please # to comment.