mta_sdk/
client.rs

1use reqwest::Client;
2
3/// A struct representing authentication credentials.
4pub struct Auth {
5    /// The username for authentication.
6    pub username: String,
7    /// The password for authentication.
8    pub password: String,
9}
10
11/// A struct representing the configuration for making requests to the MTA service.
12pub struct Mta {
13    /// The IP address of the MTA server.
14    pub ip: String,
15    /// The port number of the MTA server.
16    pub port: u16,
17    /// The authentication credentials for accessing the MTA server.
18    pub auth: Auth,
19    /// Determines whether HTTP or HTTPS should be used for requests.
20    pub http: bool,
21}
22
23impl Mta{
24    /// Creates a new `Mta` instance.
25    ///
26    /// # Arguments
27    ///
28    /// * `ip` - The IP address of the MTA server.
29    /// * `port` - The port number of the MTA server.
30    /// * `auth` - Authentication credentials for accessing the MTA server.
31    /// * `http` - Whether to use HTTP (`true`) or HTTPS (`false`) for requests.
32    ///
33    /// # Example
34    ///```rust
35    /// use mta_sdk::client;
36    ///
37    /// let auth = client::Auth {
38    ///     username: "user".to_string(),
39    ///     password: "pass".to_string(),
40    /// };
41    ///
42    /// let mta = client::Mta::new("127.0.0.1".to_string(), 22005, auth, true);
43    ///```
44    pub fn new(ip: String, port: u16, auth: Auth, http: bool) -> Mta {
45        Mta {
46            ip,
47            port,
48            auth,
49            http
50        }
51    }
52
53        /// Makes a remote call to the MTA service.
54        ///
55        /// This method sends a POST request to the specified resource and function
56        /// on the MTA server, passing the provided arguments.
57        ///
58        /// # Arguments
59        ///
60        /// * `resource` - The resource to call.
61        /// * `function` - The function to invoke.
62        /// * `args` - The arguments for the function call.
63        ///
64        /// # Returns
65        ///
66        /// Returns a `Result` containing the response text if the request is successful,
67        /// or an `Errors` enum if an error occurs during the request.
68        ///
69        /// # Errors
70        ///
71        /// Returns an `HTTP404ERROR` variant of the `Errors` enum if there is a request error.
72        ///
73        /// # Example
74        ///
75        /// ```rust
76        /// use mta_sdk::client;
77        ///
78        /// #[tokio::main]
79        /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
80        ///     let auth = client::Auth {
81        ///         username: "user".to_string(),
82        ///         password: "pass".to_string(),
83        ///     };
84        ///
85        ///     let mta_instance = client::Mta::new("127.0.0.1".to_string(), 22005, auth, true);
86        ///     let response = mta_instance.call("resource", "function", vec!["arg1".to_string()]).await?;
87        ///     println!("Response: {}", response);
88        ///
89        ///     Ok(())
90        /// }
91        /// ```
92    pub async fn call(&self, resource: &str, function: &str, args: Vec<String>) -> Result<String, crate::error::Errors> {
93        let url = format!("{}{}/call/{}", self.get_uri(), resource, function);
94
95        let client = Client::new();
96        let res = client.post(&url)
97            .header("Content-Type", "application/json")
98            .basic_auth(&self.auth.username, Some(&self.auth.password))
99            .json(&args)
100            .send()
101            .await;
102
103        match res {
104            Ok(res) => {
105                let status = res.status().to_string();
106                if status == "200 OK" {
107                    let body = res.text().await.unwrap();
108                    Ok(body)
109                } else {
110                    let err = crate::error::Errors::RequestError(format!("The server returned an error. Status: {} 🛑 .", status));
111                    Err(err)
112                }
113            },
114            Err(_err) => {
115                let err = crate::error::Errors::RequestError("There was a failure in transmitting your request to the server. We recommend checking the connection and trying again.".to_string());
116                Err(err)
117            }
118        }
119    }
120
121    /// Returns the URI based on the configured HTTP/HTTPS setting.
122    ///
123    ///
124    /// # Example
125    ///
126    /// ```rust
127    /// use mta_sdk::client;
128    ///
129    /// let auth = client::Auth {
130    ///     username: "user".to_string(),
131    ///     password: "pass".to_string(),
132    /// };
133    ///
134    /// let instance = client::Mta::new("127.0.0.1".to_string(), 22005, auth, true);
135    ///
136    /// let uri = instance.get_uri();
137    /// println!("URI: {}", uri);
138    /// ```
139    pub fn get_uri (&self) -> String {
140        if self.http {
141            format!("http://{}:{}/", self.ip, self.port)
142        } else {
143            format!("https://{}:{}/", self.ip, self.port)
144        }
145    }
146}