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
extern crate serde;
extern crate serde_json;
extern crate url;

use reqwest::{Client, Method, RequestBuilder};
use serde::de::DeserializeOwned;
use thiserror::Error;

pub mod api;
pub mod models;

#[derive(Clone, Debug)]
pub struct NomadClient {
    client: Client,
    config: Config,
}

impl NomadClient {
    pub fn new(config: Config) -> Self {
        return NomadClient {
            client: Client::new(),
            config,
        };
    }

    pub fn config(&self) -> &Config {
        &self.config
    }

    pub fn get_base_url(&self) -> String {
        format!("{}:{}/{}", self.config.base_url, self.config.port, self.config.api_version)
    }

    pub fn get_endpoint(&self, endpoint: &str) -> String {
        if endpoint.starts_with("/") {
            return format!("{}{}", self.get_base_url(), endpoint);
        }

        return format!("{}/{}", self.get_base_url(), endpoint);
    }

    pub fn request(&self, method: Method, endpoint: &str) -> RequestBuilder {
        self.client.request(method, &self.get_endpoint(endpoint))
    }

    async fn send_plain(&self, req: RequestBuilder) -> Result<String, ClientError> {
        let req_result = req.build();
        if req_result.is_err() {
            return Err(ClientError::RequestError(req_result.err().unwrap().to_string()));
        }

        let req = req_result.unwrap();

        match self.client.execute(req).await {
            Ok(response) => {
                let status = response.status();
                let body_result = response.text().await;

                match body_result {
                    Ok(body) => {
                        if status.is_success() {
                            Ok(body)
                        } else {
                            Err(ClientError::ServerError(status.as_u16(), body))
                        }
                    }
                    Err(err) => Err(ClientError::NetworkError(err.to_string())),
                }
            }
            Err(err) => Err(ClientError::NetworkError(err.to_string()))
        }
    }

    async fn send<TResponse: DeserializeOwned>(&self, req: RequestBuilder) -> Result<TResponse, ClientError> {
        let req_result = req.build();
        if req_result.is_err() {
            return Err(ClientError::RequestError(req_result.err().unwrap().to_string()));
        }

        let req = req_result.unwrap();

        match self.client.execute(req).await {
            Ok(response) => {
                let status = response.status();
                return if status.is_success() {
                    let body = response.json::<TResponse>().await;
                    match body {
                        Ok(val) => Ok(val),
                        Err(err) => Err(ClientError::DeserializationError(err.to_string()))
                    }
                } else {
                    let error_body = response.text().await;
                    match error_body {
                        Ok(body) => Err(ClientError::ServerError(status.as_u16(), body)),
                        Err(err) => Err(ClientError::NetworkError(err.to_string()))
                    }
                };
            }
            Err(err) => Err(ClientError::NetworkError(err.to_string()))
        }
    }
}

impl Default for NomadClient {
    fn default() -> Self {
        NomadClient {
            config: Config::default(),
            client: Client::new(),
        }
    }
}


#[derive(Clone, Debug)]
pub struct Config {
    pub base_url: String,
    pub port: u16,
    pub api_version: String,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            base_url: "http://localhost".into(),
            port: 4646,
            api_version: "v1".into(),
        }
    }
}

#[derive(Error, Debug)]
pub enum ClientError {
    #[error("Error building the request: {0}")]
    RequestError(String),
    #[error("Response could not be deserialized: {0}")]
    DeserializationError(String),
    #[error("The api has returned an error: [{0}] '{0}'")]
    ServerError(u16, String),
    #[error("A network related error occurred: {0}")]
    NetworkError(String),
}