use serde::de::DeserializeOwned; use serde::Serialize; use crate::model::{ CreateEncryptionDevice, CreateRoutine, CreateTask, EncryptionDevice, EncryptionRecipient, RescheduleTask, Routine, Task, }; pub struct ApiClient { base_url: String, token: Option, } impl ApiClient { pub fn new(base_url: String, token: Option) -> Self { Self { base_url: base_url.trim_end_matches('/').to_owned(), token, } } pub fn list_tasks(&self, date: &str) -> Result, String> { self.get(&format!("/v1/tasks?date={date}")) } pub fn list_overdue_tasks(&self, before: &str) -> Result, String> { self.get(&format!("/v1/tasks/overdue?before={before}")) } pub fn list_routines(&self) -> Result, String> { self.get("/v1/routines") } pub fn list_archived_tasks(&self) -> Result, String> { self.get("/v1/tasks/archived") } pub fn list_encryption_devices(&self) -> Result, String> { self.get("/v1/encryption/devices") } pub fn list_encryption_recipients(&self) -> Result, String> { self.get("/v1/encryption/recipients") } pub fn create_encryption_device(&self, device: &CreateEncryptionDevice) -> Result<(), String> { self.send_json("/v1/encryption/devices", device) } pub fn revoke_encryption_device(&self, id: i64) -> Result<(), String> { self.send_empty("POST", &format!("/v1/encryption/devices/{id}/revoke")) } pub fn create_task(&self, task: &CreateTask) -> Result<(), String> { self.send_json("/v1/tasks", task) } pub fn update_task(&self, id: i64, task: &CreateTask) -> Result<(), String> { let body = serde_json::to_string(task).map_err(|error| error.to_string())?; let response = self .authorize(minreq::put(self.url(&format!("/v1/tasks/{id}")))) .with_header("Content-Type", "application/json") .with_body(body) .send() .map_err(transport_error)?; check_status(response) } pub fn create_routine(&self, routine: &CreateRoutine) -> Result<(), String> { self.send_json("/v1/routines", routine) } pub fn complete_task(&self, id: i64) -> Result<(), String> { self.send_empty("POST", &format!("/v1/tasks/{id}/complete")) } pub fn archive_task(&self, id: i64) -> Result<(), String> { self.send_empty("POST", &format!("/v1/tasks/{id}/archive")) } pub fn restore_task(&self, id: i64) -> Result<(), String> { self.send_empty("POST", &format!("/v1/tasks/{id}/restore")) } pub fn delete_task(&self, id: i64) -> Result<(), String> { self.send_empty("DELETE", &format!("/v1/tasks/{id}")) } pub fn reschedule_task(&self, id: i64, date: &str) -> Result<(), String> { self.send_json( &format!("/v1/tasks/{id}/reschedule"), &RescheduleTask { scheduled_date: date.to_owned(), }, ) } fn get(&self, path: &str) -> Result { let response = self .authorize(minreq::get(self.url(path))) .send() .map_err(transport_error)?; let body = response.as_str().map_err(|error| error.to_string())?; if !(200..300).contains(&response.status_code) { return Err(api_error(response.status_code, body)); } serde_json::from_str(body).map_err(|error| format!("invalid server response: {error}")) } fn send_json(&self, path: &str, value: &T) -> Result<(), String> { let body = serde_json::to_string(value).map_err(|error| error.to_string())?; let response = self .authorize(minreq::post(self.url(path))) .with_header("Content-Type", "application/json") .with_body(body) .send() .map_err(transport_error)?; check_status(response) } fn send_empty(&self, method: &str, path: &str) -> Result<(), String> { let request = match method { "POST" => minreq::post(self.url(path)), "DELETE" => minreq::delete(self.url(path)), _ => return Err(format!("unsupported HTTP method: {method}")), }; let response = self.authorize(request).send().map_err(transport_error)?; check_status(response) } fn authorize(&self, request: minreq::Request) -> minreq::Request { match &self.token { Some(token) => request.with_header("Authorization", format!("Bearer {token}")), None => request, } } fn url(&self, path: &str) -> String { format!("{}{path}", self.base_url) } } fn check_status(response: minreq::Response) -> Result<(), String> { if (200..300).contains(&response.status_code) { return Ok(()); } let body = response.as_str().unwrap_or(""); Err(api_error(response.status_code, body)) } fn api_error(status: i32, body: &str) -> String { serde_json::from_str::(body) .ok() .and_then(|value| value["error"].as_str().map(str::to_owned)) .unwrap_or_else(|| format!("server returned HTTP {status}")) } fn transport_error(error: minreq::Error) -> String { format!("cannot reach routine-server: {error}") } #[cfg(test)] mod tests { use super::*; #[test] fn joins_base_url_and_path_once() { let client = ApiClient::new("http://localhost:8090/".to_owned(), None); assert_eq!(client.url("/health"), "http://localhost:8090/health"); } #[test] fn reads_json_error_message() { assert_eq!(api_error(400, r#"{"error":"bad date"}"#), "bad date"); } }