1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
extern crate reqwest;
extern crate serde_json;
use reqwest::Client;
use crate::util::RouxError;
mod responses;
use responses::{Moderators, Submissions};
pub struct Subreddit {
pub name: String,
url: String,
client: Client,
}
impl Subreddit {
pub fn new(name: &str) -> Subreddit {
let subreddit_url = format!("https://www.reddit.com/r/{}", name);
Subreddit {
name: name.to_owned(),
url: subreddit_url,
client: Client::new(),
}
}
pub fn moderators(&self) -> Result<Moderators, RouxError> {
Ok(self.client
.get(&format!("{}/about/moderators/.json", self.url))
.send()?
.json::<Moderators>()?)
}
fn get_feed(&self, ty: &str, limit: u32) -> Result<Submissions, RouxError> {
Ok(self.client
.get(&format!("{}/{}.json?limit={}", self.url, ty, limit))
.send()?
.json::<Submissions>()?)
}
pub fn hot(&self, limit: u32) -> Result<Submissions, RouxError> {
self.get_feed("hot", limit)
}
pub fn rising(&self, limit: u32) -> Result<Submissions, RouxError> {
self.get_feed("rising", limit)
}
pub fn top(&self, limit: u32) -> Result<Submissions, RouxError> {
self.get_feed("top", limit)
}
}
#[cfg(test)]
mod tests {
use super::Subreddit;
#[test]
fn test_no_auth() {
let subreddit = Subreddit::new("rust");
let moderators = subreddit.moderators();
assert!(moderators.is_ok());
let hot = subreddit.hot(25);
assert!(hot.is_ok());
let rising = subreddit.rising(25);
assert!(rising.is_ok());
let top = subreddit.top(25);
assert!(top.is_ok());
}
}