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
use nanoserde::DeJson;
#[allow(dead_code)]
#[derive(DeJson)]
pub struct Comic {
    pub month: String,
    pub num: i32,
    pub year: String,
    pub safe_title: String,
    pub transcript: String,
    pub alt: String,
    pub img: String,
    pub title: String,
    pub day: String,
}

impl Comic {
    pub fn new(num: Option<i32>) -> Result<Comic, nanoserde::DeJsonErr> {
        match num {
            Some(_) => {
                println!("{:#?}", num);
                return Comic::deserialize_json(dbg!(&ureq::get(&format!(
                    "https://xkcd.com/{:#?}/info.0.json",
                    num.unwrap()
                ))
                .call()
                .unwrap()
                .into_string()
                .unwrap(),));
            }
            None => {
                return Comic::deserialize_json(
                    &ureq::get("https://xkcd.com/info.0.json")
                        .call()
                        .unwrap()
                        .into_string()
                        .unwrap(),
                );
            }
        }
    }
}

#[cfg(test)]
#[test]
fn test_get_641() {
    let x = Comic::new(Some(642)).unwrap();
    assert_eq!(x.num, 642);
    assert_eq!(x.year, "2009");
}