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
use reqwest::{Client, ClientBuilder, Method, RequestBuilder, Response, Url}; use reqwest::header::{HeaderMap, InvalidHeaderValue}; use serde::{Serialize, de::DeserializeOwned}; use core::fmt; #[cfg(test)] mod tests { use super::*; fn get_test_url() -> Url { DEFAULT_ROOT.parse().expect("failed to parse default root url for testing") } fn get_test_auth() -> UserAuth { UserAuth { user_id: String::from("Some User"), api_key: String::from("TEST TOKEN"), } } fn get_test_client_id() -> ClientId { ClientId { creator_id: "Creator Id", app_name: "habitica-api-rs-tests", } } #[test] fn test_client_default() { let client = HabiticaClient::new(get_test_url(), get_test_client_id()) .expect("failed to build test client"); let root = client.root; assert_eq!(client.auth, None); assert_eq!(root.scheme(), "https"); assert_eq!(root.host_str(), Some("habitica.com")); assert_eq!(root.path(), "/api/v3"); assert_eq!(root.query(), None); assert_eq!(root.username(), ""); assert_eq!(root.password(), None); assert_eq!(root.port(), None); assert_eq!(root.fragment(), None); } #[test] fn test_client_creation_does_not_modify_url() { let url = get_test_url(); let new_client = HabiticaClient::new(url.clone(), get_test_client_id()) .expect("failed to build test client (without auth)"); let auth_client = HabiticaClient::with_auth(url.clone(), get_test_client_id(), get_test_auth()) .expect("failed to build test client (with auth)"); assert_eq!(new_client.root, url); assert_eq!(auth_client.root, url); } #[test] fn test_client_new_has_no_auth() { let client = HabiticaClient::new(get_test_url(), get_test_client_id()) .expect("failed to build test client"); assert_eq!(client.auth, None); } #[test] fn test_client_with_auth_has_unmodified_auth() { let auth = get_test_auth(); let client = HabiticaClient::with_auth(get_test_url(), get_test_client_id(), auth.clone()) .expect("failed to build test client"); assert_eq!(client.auth, Some(auth)); } #[test] fn test_setting_auth() { let mut client = HabiticaClient::new(get_test_url(), get_test_client_id()) .expect("failed to build test client"); let auth = get_test_auth(); assert_ne!(client.auth, Some(auth.clone())); client.set_auth(auth.clone()) .expect("failed to manually set auth"); assert_eq!(client.auth, Some(auth)) } } pub const DEFAULT_ROOT: &str = "https://habitica.com/api/v3"; pub const HEADER_KEY_XCLIENT: &str = "X-Client"; pub const HEADER_KEY_API_USER: &str = "X-API-User"; pub const HEADER_KEY_API_KEY: &str = "X-API-Key"; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { BuildRequest(reqwest::Error), BuildReqwestClient(reqwest::Error), InvalidHeaderValue(InvalidHeaderValue), UrlParse(url::ParseError), Request(reqwest::Error), } impl From<url::ParseError> for Error { fn from(v: url::ParseError) -> Self { Error::UrlParse(v) } } impl From<InvalidHeaderValue> for Error { fn from(v: InvalidHeaderValue) -> Self { Error::InvalidHeaderValue(v) } } #[derive(Clone, Debug, PartialEq)] pub struct ClientId { creator_id: &'static str, app_name: &'static str, } impl fmt::Display for ClientId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}-{}", self.creator_id, self.app_name) } } #[derive(Clone, Debug, PartialEq)] pub struct UserAuth { pub user_id: String, pub api_key: String, } #[derive(Clone, Debug)] pub struct HabiticaClient { root: Url, client: Client, client_id: ClientId, auth: Option<UserAuth>, } impl HabiticaClient { fn internal_new(root: Url, client_id: ClientId, auth: Option<UserAuth>) -> Result<Self> { let client = Self::internal_new_client(&client_id, auth.as_ref())? .build() .map_err(Error::BuildReqwestClient)?; let output = Self { auth, root, client, client_id, }; Ok(output) } fn internal_new_client(client_id: &ClientId, auth: Option<&UserAuth>) -> Result<ClientBuilder> { let mut headers = HeaderMap::new(); let client = Client::builder(); if let Some(auth) = auth { headers.insert(HEADER_KEY_API_USER, auth.user_id.parse().map_err(Error::InvalidHeaderValue)?); headers.insert(HEADER_KEY_API_KEY, auth.api_key.parse().map_err(Error::InvalidHeaderValue)?); } headers.insert(HEADER_KEY_XCLIENT, client_id.to_string().parse().map_err(Error::InvalidHeaderValue)?); Ok(client.default_headers(headers)) } pub fn new(root: Url, client_id: ClientId) -> Result<Self> { Self::internal_new(root, client_id, None) } pub fn with_auth(root: Url, client_id: ClientId, auth: UserAuth) -> Result<Self> { Self::internal_new(root, client_id, Some(auth)) } pub fn set_auth(&mut self, auth: UserAuth) -> Result<()> { self.auth = Some(auth); self.client = Self::internal_new_client( &self.client_id, self.auth.as_ref())? .build() .map_err(Error::BuildReqwestClient)?; Ok(()) } pub async fn request<S>(&self, method: Method, path: &str, body: Option<S>, query: Option<S>) -> Result<Response> where S: Serialize { let new_url = self.root.join(path)?; let mut req = self.client.request(method, new_url); if let Some(body) = body { req = req.json(&body); } if let Some(query) = query { req = req.query(&query); } let req = req.build().map_err(Error::BuildRequest)?; self.client.execute(req).await .map_err(Error::Request) } }