revolt_database/models/bots/ops/
reference.rs

1use revolt_result::Result;
2
3use crate::ReferenceDb;
4use crate::{Bot, FieldsBot, PartialBot};
5
6use super::AbstractBots;
7
8#[async_trait]
9impl AbstractBots for ReferenceDb {
10    /// Insert new bot into the database
11    async fn insert_bot(&self, bot: &Bot) -> Result<()> {
12        let mut bots = self.bots.lock().await;
13        if bots.contains_key(&bot.id) {
14            Err(create_database_error!("insert", "bot"))
15        } else {
16            bots.insert(bot.id.to_string(), bot.clone());
17            Ok(())
18        }
19    }
20
21    /// Fetch a bot by its id
22    async fn fetch_bot(&self, id: &str) -> Result<Bot> {
23        let bots = self.bots.lock().await;
24        bots.get(id).cloned().ok_or_else(|| create_error!(NotFound))
25    }
26
27    /// Fetch a bot by its token
28    async fn fetch_bot_by_token(&self, token: &str) -> Result<Bot> {
29        let bots = self.bots.lock().await;
30        bots.values()
31            .find(|bot| bot.token == token)
32            .cloned()
33            .ok_or_else(|| create_error!(NotFound))
34    }
35
36    /// Fetch bots owned by a user
37    async fn fetch_bots_by_user(&self, user_id: &str) -> Result<Vec<Bot>> {
38        let bots = self.bots.lock().await;
39        Ok(bots
40            .values()
41            .filter(|bot| bot.owner == user_id)
42            .cloned()
43            .collect())
44    }
45
46    /// Get the number of bots owned by a user
47    async fn get_number_of_bots_by_user(&self, user_id: &str) -> Result<usize> {
48        let bots = self.bots.lock().await;
49        Ok(bots.values().filter(|bot| bot.owner == user_id).count())
50    }
51
52    /// Update bot with new information
53    async fn update_bot(
54        &self,
55        id: &str,
56        partial: &PartialBot,
57        remove: Vec<FieldsBot>,
58    ) -> Result<()> {
59        let mut bots = self.bots.lock().await;
60        if let Some(bot) = bots.get_mut(id) {
61            for field in remove {
62                #[allow(clippy::disallowed_methods)]
63                bot.remove_field(&field);
64            }
65
66            bot.apply_options(partial.clone());
67            Ok(())
68        } else {
69            Err(create_error!(NotFound))
70        }
71    }
72
73    /// Delete a bot from the database
74    async fn delete_bot(&self, id: &str) -> Result<()> {
75        let mut bots = self.bots.lock().await;
76        if bots.remove(id).is_some() {
77            Ok(())
78        } else {
79            Err(create_error!(NotFound))
80        }
81    }
82}