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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use std::default::Default;
use std::time::Duration;

use reqwest::Method;
use serde_json::Value;

use crate::utils;

pub struct Options {
    pub method: Method,
    pub body: String,
    pub timeout: Duration,
}

impl Default for Options {
    fn default() -> Self {
        Options {
            method: Method::GET,
            body: String::new(),
            timeout: Duration::from_secs(6),
        }
    }
}

pub async fn fetch(url: String, options: Options) -> anyhow::Result<Value> {
    let client = reqwest::Client::new();

    let response = client
        .request(options.method, url)
        .body(options.body)
        .timeout(options.timeout)
        .send()
        .await?;
    if !response.status().is_success() {
        let err = response.text().await?;
        return Err(anyhow::anyhow!(err));
    }

    let body = response.text().await?;
    let v: Value = serde_json::from_str(&body)?;
    if v["error"] != "" {
        return Err(anyhow::anyhow!(v["error"].as_str().unwrap().to_string()));
    }

    Ok(v["data"].to_owned())
}

pub async fn fetch_show_json(url: String, options: Options) {
    match fetch(url, options).await {
        Ok(result) => {
            utils::show_json(result);
        }
        Err(err) => {
            println!("Error: {}", err)
        }
    }
}

pub async fn fetch_show_ok(url: String, options: Options) {
    match fetch(url, options).await {
        Ok(_) => {
            println!("Ok")
        }
        Err(err) => {
            println!("Error: {}", err)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[tokio::test]
    async fn it_fetch_ok() {
        let mut server = mockito::Server::new_async().await;
        let url = server.url();

        let body = json!({"data": {"hello":"world"}, "error": ""}).to_string();

        server
            .mock("GET", "/hello")
            .with_status(200)
            .with_body(body)
            .create_async()
            .await;

        let result = fetch(format!("{}{}", url, "/hello"), Options::default())
            .await
            .unwrap();

        assert_eq!("{\"hello\":\"world\"}", result.to_string());
    }

    #[tokio::test]
    async fn it_fetch_status_failed() {
        let mut server = mockito::Server::new_async().await;
        let url = server.url();

        let body = "404 page not found";

        server
            .mock("GET", "/")
            .with_status(404)
            .with_body(body)
            .create_async()
            .await;

        let result = fetch(format!("{}{}", url, "/"), Options::default())
            .await
            .unwrap_err();

        assert_eq!(body, result.to_string());
    }

    #[tokio::test]
    async fn it_fetch_error() {
        let mut server = mockito::Server::new_async().await;
        let url = server.url();

        let body = json!({"data": null, "error": "`id` not found!"}).to_string();

        server
            .mock("POST", "/job")
            .with_status(200)
            .with_body(body)
            .create_async()
            .await;

        let result = fetch(
            format!("{}{}", url, "/job"),
            Options {
                method: Method::POST,
                ..Default::default()
            },
        )
        .await
        .unwrap_err();

        assert_eq!("`id` not found!", result.to_string());
    }
}