use reqwest::Client;
use super::retry::{RetryConfig, deliver_with_retry, is_success_2xx};
use super::{Event, EventSubscriber, SubscriberFuture};
pub struct WebhookSubscriber {
url: String,
client: Client,
retry_config: RetryConfig,
}
impl WebhookSubscriber {
pub fn new(url: &str) -> Self {
Self::with_retry_config(url, RetryConfig::default())
}
pub fn with_retry_config(url: &str, retry_config: RetryConfig) -> Self {
let client = retry_config.build_client();
Self {
url: url.to_string(),
client,
retry_config,
}
}
pub fn url(&self) -> &str {
&self.url
}
}
impl EventSubscriber for WebhookSubscriber {
fn name(&self) -> &str {
"webhook"
}
fn handle<'a>(&'a self, event: &'a Event) -> SubscriberFuture<'a> {
Box::pin(async move {
deliver_with_retry(
&self.retry_config,
|| self.client.post(&self.url).json(event),
is_success_2xx,
"webhook",
&self.url,
)
.await;
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn url_accessor() {
let sub = WebhookSubscriber::new("https://example.com/hook");
assert_eq!(sub.url(), "https://example.com/hook");
}
#[test]
fn name_is_webhook() {
let sub = WebhookSubscriber::new("https://example.com");
assert_eq!(sub.name(), "webhook");
}
}