use std::time::Duration;
use super::trigger::TriggerRequest;
pub const TRIGGER_URL_ENV: &str = "NOTIFICATION_API_URL";
const TRIGGER_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug, thiserror::Error)]
pub enum NotificationError {
#[error("notification center unreachable: {0}")]
Request(#[from] reqwest::Error),
#[error("notification center returned {0}")]
Status(reqwest::StatusCode),
}
#[derive(Clone)]
pub struct NotificationClient {
http: reqwest::Client,
trigger_url: String,
}
impl NotificationClient {
pub fn new(trigger_url: impl Into<String>) -> Self {
Self {
http: reqwest::Client::new(),
trigger_url: trigger_url.into(),
}
}
pub fn with_client(http: reqwest::Client, trigger_url: impl Into<String>) -> Self {
Self {
http,
trigger_url: trigger_url.into(),
}
}
pub async fn trigger(&self, request: &TriggerRequest) -> Result<(), NotificationError> {
let response = self
.http
.post(&self.trigger_url)
.json(request)
.timeout(TRIGGER_TIMEOUT)
.send()
.await?;
if !response.status().is_success() {
return Err(NotificationError::Status(response.status()));
}
Ok(())
}
}