//! Client of the horoscope-api service (`POST /v1/natal`, `POST /v1/synastry`). //! //! Requests and responses are passed as JSON: the horoscope service validates //! the birth data itself, and its error objects are handed back unchanged so //! callers can show them to the user. use std::time::Duration; use serde_json::Value; #[derive(Debug, thiserror::Error)] pub enum HoroscopeError { /// The service rejected the input (4xx); `body` is its `{"error": {...}}` object. #[error("horoscope service rejected the request ({status})")] Rejected { status: u16, body: Value }, /// The service is unreachable or failed (5xx, timeout, invalid response). #[error("horoscope service unavailable: {0}")] Unavailable(String), } #[derive(Clone)] pub struct HoroscopeClient { base_url: String, http: reqwest::Client, } impl HoroscopeClient { pub fn new(base_url: impl Into) -> Self { let http = reqwest::Client::builder() .timeout(Duration::from_secs(15)) .build() .expect("static reqwest configuration is valid"); Self { base_url: base_url.into().trim_end_matches('/').to_string(), http } } /// `POST /v1/natal` pub async fn natal(&self, request: &Value) -> Result { self.post("/v1/natal", request).await } /// `POST /v1/synastry` pub async fn synastry(&self, request: &Value) -> Result { self.post("/v1/synastry", request).await } /// `POST /v1/forecast` pub async fn forecast(&self, request: &Value) -> Result { self.post("/v1/forecast", request).await } /// `GET /v1/countries` pub async fn countries(&self) -> Result { self.get("/v1/countries", &[]).await } /// `GET /v1/places?country=&q=&limit=` pub async fn places(&self, country: &str, query: &str, limit: u32) -> Result { self.get("/v1/places", &[("country", country), ("q", query), ("limit", &limit.to_string())]).await } async fn get(&self, path: &str, query: &[(&str, &str)]) -> Result { let response = self .http .get(format!("{}{path}", self.base_url)) .query(query) .send() .await .map_err(|e| HoroscopeError::Unavailable(e.to_string()))?; Self::answer(response).await } async fn post(&self, path: &str, body: &Value) -> Result { let response = self .http .post(format!("{}{path}", self.base_url)) .json(body) .send() .await .map_err(|e| HoroscopeError::Unavailable(e.to_string()))?; Self::answer(response).await } async fn answer(response: reqwest::Response) -> Result { let status = response.status(); let body: Value = response.json().await.map_err(|e| HoroscopeError::Unavailable(e.to_string()))?; if status.is_success() { Ok(body) } else if status.is_client_error() { Err(HoroscopeError::Rejected { status: status.as_u16(), body }) } else { Err(HoroscopeError::Unavailable(format!("{status}: {body}"))) } } }