Skip to main content

stoat/ext/
webhook.rs

1use async_trait::async_trait;
2use stoat_models::v0::Webhook;
3
4use crate::{
5    Error, HttpClient, Result,
6    builders::{EditWebhookBuilder, ExecuteWebhookBuilder},
7};
8
9#[async_trait]
10pub trait WebhookExt: Sized {
11    async fn from_token(
12        http: impl AsRef<HttpClient> + Send,
13        webhook_id: &str,
14        token: &str,
15    ) -> Result<Self>;
16    async fn from_url(http: impl AsRef<HttpClient> + Send, url: &str) -> Result<Self>;
17    async fn delete(&self, http: impl AsRef<HttpClient> + Send) -> Result<()>;
18    fn edit(&self, http: impl AsRef<HttpClient>) -> EditWebhookBuilder;
19    fn execute(&self, http: impl AsRef<HttpClient>) -> ExecuteWebhookBuilder;
20}
21
22#[async_trait]
23impl WebhookExt for Webhook {
24    async fn from_token(
25        http: impl AsRef<HttpClient> + Send,
26        webhook_id: &str,
27        token: &str,
28    ) -> Result<Self> {
29        http.as_ref().fetch_webhook_token(webhook_id, token).await
30    }
31
32    async fn from_url(http: impl AsRef<HttpClient> + Send, url: &str) -> Result<Self> {
33        let mut components = url.split('/').rev();
34        let token = components.next().ok_or(Error::InvalidUrl)?;
35        let id = components.next().ok_or(Error::InvalidUrl)?;
36
37        Self::from_token(http, id, token).await
38    }
39
40    async fn delete(&self, http: impl AsRef<HttpClient> + Send) -> Result<()> {
41        if let Some(token) = &self.token {
42            http.as_ref().delete_webhook_token(&self.id, token).await
43        } else {
44            http.as_ref().delete_webhook(&self.id).await
45        }
46    }
47
48    fn edit(&self, http: impl AsRef<HttpClient>) -> EditWebhookBuilder {
49        EditWebhookBuilder::new(http.as_ref().clone(), self.id.clone(), self.token.clone())
50    }
51
52    fn execute(&self, http: impl AsRef<HttpClient>) -> ExecuteWebhookBuilder {
53        ExecuteWebhookBuilder::new(
54            http.as_ref().clone(),
55            self.id.clone(),
56            self.token.clone().expect("Webhook missing token."),
57        )
58    }
59}