monzo/client/inner/
quick.rs

1use crate::{client, client::Client, endpoints::Endpoint};
2
3/// A quick and dirty Monzo API client.
4///
5/// This client is easy to construct, because all you need is an access token.
6/// This client is not capable of refreshing the access token, hence this must
7/// be managed externally.
8#[derive(Debug, Clone)]
9#[must_use]
10pub struct Quick {
11    http_client: reqwest::Client,
12    access_token: String,
13    url: String,
14}
15
16impl Client<Quick> {
17    /// Create a new Monzo Client..
18    ///
19    /// This `Client` needs only an access token to authenticate against
20    /// the Monzo API, but is incapable of refreshing its access if the
21    /// token expires.
22    pub fn new(access_token: impl Into<String>) -> Self {
23        let http_client = reqwest::Client::default();
24        let inner_client = Quick {
25            http_client,
26            access_token: access_token.into(),
27            url: "https://api.monzo.com".into(),
28        };
29        Self { inner_client }
30    }
31
32    /// Upgrade a Client by adding refresh tokens.
33    ///
34    /// A client that has refresh tokens is able to refresh it's authentication
35    /// when the access token expires.
36    pub fn with_refresh_tokens(
37        self,
38        client_id: impl Into<String>,
39        client_secret: impl Into<String>,
40        refresh_token: impl Into<String>,
41    ) -> Client<client::inner::Refreshable> {
42        Client::from_quick_client(self.inner_client, client_id, client_secret, refresh_token)
43    }
44}
45
46impl client::Inner for Quick {
47    async fn execute<E>(&self, endpoint: &E) -> reqwest::Result<reqwest::Response>
48    where
49        E: Endpoint,
50    {
51        let mut request = self
52            .http_client
53            .request(E::METHOD, self.url.clone() + endpoint.endpoint());
54
55        if E::AUTH_REQUIRED {
56            request = request.bearer_auth(&self.access_token);
57        }
58
59        if let Some(query) = endpoint.query() {
60            request = request.query(query);
61        }
62
63        if let Some(form) = endpoint.form() {
64            request = request.form(form);
65        }
66
67        if let Some(json) = endpoint.json() {
68            request = request.json(json);
69        }
70
71        request.send().await
72    }
73
74    fn access_token(&self) -> &String {
75        &self.access_token
76    }
77
78    fn set_access_token(&mut self, access_token: String) {
79        self.access_token = access_token;
80    }
81
82    fn url(&self) -> &str {
83        &self.url
84    }
85}