|
| 1 | +//! Client for the [EventsourcingDB](https://www.eventsourcingdb.io/) API. |
| 2 | +//! |
| 3 | +//! To use the client, create it with the base URL and API token of your [EventsourcingDB](https://www.eventsourcingdb.io/) instance. |
| 4 | +//! ``` |
| 5 | +//! # tokio_test::block_on(async { |
| 6 | +//! # let container = eventsourcingdb_client_rust::container::Container::start_default().await.unwrap(); |
| 7 | +//! let db_url = "http://localhost:3000/"; |
| 8 | +//! let api_token = "secrettoken"; |
| 9 | +//! # let db_url = container.get_base_url().await.unwrap(); |
| 10 | +//! # let api_token = container.get_api_token(); |
| 11 | +//! let client = eventsourcingdb_client_rust::client::Client::new(db_url, api_token); |
| 12 | +//! client.ping().await.expect("Failed to ping"); |
| 13 | +//! client.verify_api_token().await.expect("Failed to verify API token"); |
| 14 | +//! # }) |
| 15 | +//! ``` |
| 16 | +//! |
| 17 | +//! With the code above you can verify that the DB is reachable and that the API token is valid. |
| 18 | +//! If this works, it means that the client is correctly configured and you can use it to make requests to the DB. |
| 19 | +
|
| 20 | +mod client_request; |
| 21 | + |
| 22 | +use client_request::ClientRequest; |
| 23 | + |
| 24 | +use reqwest; |
| 25 | +use url::Url; |
| 26 | + |
| 27 | +use crate::{error::ClientError, event::ManagementEvent}; |
| 28 | + |
| 29 | +/// Client for an [EventsourcingDB](https://www.eventsourcingdb.io/) instance. |
| 30 | +#[derive(Debug)] |
| 31 | +pub struct Client { |
| 32 | + base_url: Url, |
| 33 | + api_token: String, |
| 34 | + client: reqwest::Client, |
| 35 | +} |
| 36 | + |
| 37 | +impl Client { |
| 38 | + /// Creates a new client instance based on the base URL and API token |
| 39 | + pub fn new(base_url: Url, api_token: impl Into<String>) -> Self { |
| 40 | + Client { |
| 41 | + base_url, |
| 42 | + api_token: api_token.into(), |
| 43 | + client: reqwest::Client::new(), |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + /// Get the base URL of the client to use for API calls |
| 48 | + /// ``` |
| 49 | + /// # use url::Url; |
| 50 | + /// # use eventsourcingdb_client_rust::client::Client; |
| 51 | + /// # let client = Client::new("http://localhost:8080/".parse().unwrap(), "token"); |
| 52 | + /// let base_url = client.get_base_url(); |
| 53 | + /// # assert_eq!(base_url.as_str(), "http://localhost:8080/"); |
| 54 | + /// ``` |
| 55 | + #[must_use] |
| 56 | + pub fn get_base_url(&self) -> &Url { |
| 57 | + &self.base_url |
| 58 | + } |
| 59 | + |
| 60 | + /// Get the API token of the client to use for API calls |
| 61 | + /// ``` |
| 62 | + /// # use eventsourcingdb_client_rust::client::Client; |
| 63 | + /// # use url::Url; |
| 64 | + /// # let client = Client::new("http://localhost:8080/".parse().unwrap(), "secrettoken"); |
| 65 | + /// let api_token = client.get_api_token(); |
| 66 | + /// # assert_eq!(api_token, "secrettoken"); |
| 67 | + /// ``` |
| 68 | + #[must_use] |
| 69 | + pub fn get_api_token(&self) -> &str { |
| 70 | + &self.api_token |
| 71 | + } |
| 72 | + |
| 73 | + /// Utility function to request an endpoint of the API. |
| 74 | + /// |
| 75 | + /// # Errors |
| 76 | + /// This function will return an error if the request fails or if the URL is invalid. |
| 77 | + async fn request(&self, endpoint: ClientRequest) -> Result<reqwest::Response, ClientError> { |
| 78 | + let url = self |
| 79 | + .base_url |
| 80 | + .join(endpoint.url_path()) |
| 81 | + .map_err(ClientError::URLParseError)?; |
| 82 | + |
| 83 | + let request = match endpoint.method() { |
| 84 | + reqwest::Method::GET => self.client.get(url), |
| 85 | + reqwest::Method::POST => self.client.post(url), |
| 86 | + _ => return Err(ClientError::InvalidRequestMethod), |
| 87 | + } |
| 88 | + .header("Authorization", format!("Bearer {}", self.api_token)); |
| 89 | + let request = if let Some(body) = endpoint.json() { |
| 90 | + request |
| 91 | + .header("Content-Type", "application/json") |
| 92 | + .json(&body?) |
| 93 | + } else { |
| 94 | + request |
| 95 | + }; |
| 96 | + |
| 97 | + let response = request.send().await?; |
| 98 | + |
| 99 | + if response.status().is_success() { |
| 100 | + Ok(response) |
| 101 | + } else { |
| 102 | + Err(ClientError::DBError( |
| 103 | + response.status(), |
| 104 | + response.text().await.unwrap_or_default(), |
| 105 | + )) |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + /// Pings the DB instance to check if it is reachable. |
| 110 | + /// |
| 111 | + /// ``` |
| 112 | + /// # tokio_test::block_on(async { |
| 113 | + /// # let container = eventsourcingdb_client_rust::container::Container::start_default().await.unwrap(); |
| 114 | + /// let db_url = "http://localhost:3000/"; |
| 115 | + /// let api_token = "secrettoken"; |
| 116 | + /// # let db_url = container.get_base_url().await.unwrap(); |
| 117 | + /// # let api_token = container.get_api_token(); |
| 118 | + /// let client = eventsourcingdb_client_rust::client::Client::new(db_url, api_token); |
| 119 | + /// client.ping().await.expect("Failed to ping"); |
| 120 | + /// # }) |
| 121 | + /// ``` |
| 122 | + /// |
| 123 | + /// # Errors |
| 124 | + /// This function will return an error if the request fails or if the URL is invalid. |
| 125 | + pub async fn ping(&self) -> Result<(), ClientError> { |
| 126 | + let response = self.request(ClientRequest::Ping).await?; |
| 127 | + if response.json::<ManagementEvent>().await?.ty() == "io.eventsourcingdb.api.ping-received" |
| 128 | + { |
| 129 | + Ok(()) |
| 130 | + } else { |
| 131 | + Err(ClientError::PingFailed) |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + /// Verifies the API token by sending a request to the DB instance. |
| 136 | + /// |
| 137 | + /// ``` |
| 138 | + /// # tokio_test::block_on(async { |
| 139 | + /// # let container = eventsourcingdb_client_rust::container::Container::start_default().await.unwrap(); |
| 140 | + /// let db_url = "http://localhost:3000/"; |
| 141 | + /// let api_token = "secrettoken"; |
| 142 | + /// # let db_url = container.get_base_url().await.unwrap(); |
| 143 | + /// # let api_token = container.get_api_token(); |
| 144 | + /// let client = eventsourcingdb_client_rust::client::Client::new(db_url, api_token); |
| 145 | + /// client.verify_api_token().await.expect("Failed to ping"); |
| 146 | + /// # }) |
| 147 | + /// ``` |
| 148 | + /// |
| 149 | + /// # Errors |
| 150 | + /// This function will return an error if the request fails or if the URL is invalid. |
| 151 | + pub async fn verify_api_token(&self) -> Result<(), ClientError> { |
| 152 | + let response = self.request(ClientRequest::VerifyApiToken).await?; |
| 153 | + if response.json::<ManagementEvent>().await?.ty() |
| 154 | + == "io.eventsourcingdb.api.api-token-verified" |
| 155 | + { |
| 156 | + Ok(()) |
| 157 | + } else { |
| 158 | + Err(ClientError::APITokenInvalid) |
| 159 | + } |
| 160 | + } |
| 161 | +} |
0 commit comments