freedom_api/
client.rs

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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use bytes::Bytes;
use freedom_config::Config;
use reqwest::{Response, StatusCode};
use url::Url;

use crate::api::{Api, Inner, Value};

/// An asynchronous `Client` for interfacing with the ATLAS freedom API.
///
/// The client is primarily defined based on it's [`Env`](crate::config::Env)
/// and it's credentials (username and password).
#[derive(Clone, Debug)]
pub struct Client {
    pub(crate) config: Config,
    pub(crate) client: reqwest::Client,
}

impl PartialEq for Client {
    fn eq(&self, other: &Self) -> bool {
        self.config == other.config
    }
}

impl Client {
    /// Construct an API client from the provided Freedom config
    ///
    /// # Example
    ///
    /// ```
    /// # use freedom_api::prelude::*;
    /// let config = Config::builder()
    ///     .environment(Test)
    ///     .key("foo")
    ///     .secret("bar")
    ///     .build()
    ///     .unwrap();
    /// let client = Client::from_config(config);
    ///
    /// assert_eq!(client.config().key(), "foo");
    /// ```
    pub fn from_config(config: Config) -> Self {
        Self {
            config,
            client: reqwest::Client::new(),
        }
    }

    /// A convenience method for constructing an FPS client from environment variables.
    ///
    /// This function expects the following environment variables:
    ///
    /// + ATLAS_ENV: [possible values: test, prod]
    /// + ATLAS_KEY: The ATLAS freedom key registered with an account
    /// + ATLAS_SECRET: The ATLAS freedom secret registered with an account
    pub fn from_env() -> Result<Self, freedom_config::Error> {
        let config = Config::from_env()?;
        Ok(Self::from_config(config))
    }
}

impl Api for Client {
    type Container<T: Value> = Inner<T>;

    async fn get(&self, url: Url) -> Result<(Bytes, StatusCode), crate::error::Error> {
        let resp = self
            .client
            .get(url)
            .basic_auth(self.config.key(), Some(&self.config.expose_secret()))
            .send()
            .await?;

        let status = resp.status();
        let body = resp.bytes().await?;

        Ok((body, status))
    }

    async fn delete(&self, url: Url) -> Result<Response, crate::error::Error> {
        self.client
            .delete(url)
            .basic_auth(self.config.key(), Some(self.config.expose_secret()))
            .send()
            .await
            .map_err(From::from)
    }

    async fn post<S>(&self, url: Url, msg: S) -> Result<Response, crate::error::Error>
    where
        S: serde::Serialize + Sync + Send,
    {
        self.client
            .post(url)
            .basic_auth(self.config.key(), Some(self.config.expose_secret()))
            .json(&msg)
            .send()
            .await
            .map_err(From::from)
    }

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

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

#[cfg(test)]
mod tests {
    use freedom_config::Test;
    use httpmock::{
        Method::{GET, POST},
        MockServer,
    };

    use crate::Container;

    use super::*;

    fn default_client() -> Client {
        let config = Config::builder()
            .environment(Test)
            .key("foo")
            .secret("bar")
            .build()
            .unwrap();

        Client::from_config(config)
    }

    #[test]
    fn clients_are_eq_based_on_config() {
        let config = Config::builder()
            .environment(Test)
            .key("foo")
            .secret("bar")
            .build()
            .unwrap();

        let client_1 = Client::from_config(config.clone());
        let client_2 = Client::from_config(config);
        assert_eq!(client_1, client_2);
    }

    #[test]
    fn wrap_and_unwrap_inner() {
        let val = String::from("foobar");
        let inner = Inner::new(val.clone());
        assert_eq!(*inner, val);
        let unwrapped = inner.into_inner();
        assert_eq!(val, unwrapped);
    }

    #[test]
    fn load_from_env() {
        unsafe {
            std::env::set_var("ATLAS_ENV", "TEST");
            std::env::set_var("ATLAS_KEY", "foo");
            std::env::set_var("ATLAS_SECRET", "bar");
        };
        let client = Client::from_env().unwrap();
        assert_eq!(client.config().key(), "foo");
        assert_eq!(client.config().expose_secret(), "bar");
    }

    #[tokio::test]
    async fn get_ok_response() {
        const RESPONSE: &str = "it's working";
        let client = default_client();
        let server = MockServer::start();
        let addr = server.address();
        let mock = server.mock(|when, then| {
            when.method(GET).path("/testing");
            then.body(RESPONSE.as_bytes());
        });
        let url = Url::parse(&format!("http://{}/testing", addr)).unwrap();
        let (response, status) = client.get(url).await.unwrap();

        assert_eq!(response, RESPONSE.as_bytes());
        assert_eq!(status, StatusCode::OK);
        mock.assert_hits(1);
    }

    #[tokio::test]
    async fn get_err_response() {
        const RESPONSE: &str = "NOPE";
        let client = default_client();
        let server = MockServer::start();
        let addr = server.address();
        let mock = server.mock(|when, then| {
            when.method(GET).path("/testing");
            then.body(RESPONSE.as_bytes()).status(404);
        });
        let url = Url::parse(&format!("http://{}/testing", addr)).unwrap();
        let (response, status) = client.get(url).await.unwrap();

        assert_eq!(response, RESPONSE.as_bytes());
        assert_eq!(status, StatusCode::NOT_FOUND);
        mock.assert_hits(1);
    }

    #[tokio::test]
    async fn post_json() {
        let client = default_client();
        let server = MockServer::start();
        let addr = server.address();
        let json = serde_json::json!({
            "name": "foo",
            "data": 12
        });
        let json_clone = json.clone();
        let mock = server.mock(|when, then| {
            when.method(POST).path("/testing").json_body(json_clone);
            then.body(b"OK").status(200);
        });
        let url = Url::parse(&format!("http://{}/testing", addr)).unwrap();
        client.post(url, &json).await.unwrap();

        mock.assert_hits(1);
    }
}