1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use revolt_result::Result;

use crate::ReferenceDb;
use crate::{FieldsWebhook, PartialWebhook, Webhook};

use super::AbstractWebhooks;

#[async_trait]
impl AbstractWebhooks for ReferenceDb {
    /// Insert new webhook into the database
    async fn insert_webhook(&self, webhook: &Webhook) -> Result<()> {
        let mut webhooks = self.channel_webhooks.lock().await;
        if webhooks.contains_key(&webhook.id) {
            Err(create_database_error!("insert", "webhook"))
        } else {
            webhooks.insert(webhook.id.to_string(), webhook.clone());
            Ok(())
        }
    }

    /// Fetch webhook by id
    async fn fetch_webhook(&self, webhook_id: &str) -> Result<Webhook> {
        let webhooks = self.channel_webhooks.lock().await;
        webhooks
            .get(webhook_id)
            .cloned()
            .ok_or_else(|| create_error!(NotFound))
    }

    /// Fetch webhooks for channel
    async fn fetch_webhooks_for_channel(&self, channel_id: &str) -> Result<Vec<Webhook>> {
        let webhooks = self.channel_webhooks.lock().await;
        Ok(webhooks
            .values()
            .filter(|webhook| webhook.channel_id == channel_id)
            .cloned()
            .collect())
    }

    /// Update webhook with new information
    async fn update_webhook(
        &self,
        webhook_id: &str,
        partial: &PartialWebhook,
        remove: &[FieldsWebhook],
    ) -> Result<()> {
        let mut webhooks = self.channel_webhooks.lock().await;
        if let Some(webhook) = webhooks.get_mut(webhook_id) {
            for field in remove {
                #[allow(clippy::disallowed_methods)]
                webhook.remove_field(field);
            }

            webhook.apply_options(partial.clone());
            Ok(())
        } else {
            Err(create_error!(NotFound))
        }
    }

    /// Delete webhook by id
    async fn delete_webhook(&self, webhook_id: &str) -> Result<()> {
        let mut webhooks = self.channel_webhooks.lock().await;
        if webhooks.remove(webhook_id).is_some() {
            Ok(())
        } else {
            Err(create_error!(NotFound))
        }
    }
}