Skip to content

Commit d18f736

Browse files
committed
fix: Invalid result of Reddit query
When Reddit cannot find query, it should return empty list.
1 parent fb6abd8 commit d18f736

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

reddit.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,19 @@ type RedditResponse struct {
2323
} `json:"data"`
2424
}
2525

26+
// UnmarshalJSON deserialize inconsistent JSON responses to RedditResponse.
27+
// Reddit returns empty object ("{}") when there are no search results.
28+
func (r *RedditResponse) UnmarshalJSON(b []byte) error {
29+
isEmptyResponse := len(b) == 4 && string(b) == "\"{}\""
30+
if isEmptyResponse {
31+
return nil
32+
}
33+
34+
// new type prevents recursive calls to RedditResponse.UnmarshalJSON()
35+
type resp *RedditResponse
36+
return json.Unmarshal(b, resp(r))
37+
}
38+
2639
// SearchReddit searches Reddit for given query and returns list of discussions
2740
// sorted by relevance.
2841
//

reddit_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,14 @@ func ExampleSearchReddit() {
1818
// Output:
1919
// Reddit https://reddit.com/r/hypeurls/comments/17k6i1l/the_grug_brained_developer_2022/ The Grug Brained Developer (2022) https://grugbrain.dev/
2020
}
21+
22+
func ExampleSearchReddit_unknown() {
23+
client := http.Client{}
24+
query := "https://invalid.domain/query"
25+
26+
opinions := ensure.MustReturn(SearchReddit(context.TODO(), client, query))
27+
28+
fmt.Println(len(opinions))
29+
// Output:
30+
// 0
31+
}

0 commit comments

Comments
 (0)