revolt_database/models/bots/ops/
mongodb.rs

1use revolt_result::Result;
2
3use crate::{Bot, FieldsBot, PartialBot};
4use crate::{IntoDocumentPath, MongoDb};
5
6use super::AbstractBots;
7
8static COL: &str = "bots";
9
10#[async_trait]
11impl AbstractBots for MongoDb {
12    /// Insert new bot into the database
13    async fn insert_bot(&self, bot: &Bot) -> Result<()> {
14        query!(self, insert_one, COL, &bot).map(|_| ())
15    }
16
17    /// Fetch a bot by its id
18    async fn fetch_bot(&self, id: &str) -> Result<Bot> {
19        query!(self, find_one_by_id, COL, id)?.ok_or_else(|| create_error!(NotFound))
20    }
21
22    /// Fetch a bot by its token
23    async fn fetch_bot_by_token(&self, token: &str) -> Result<Bot> {
24        query!(
25            self,
26            find_one,
27            COL,
28            doc! {
29                "token": token
30            }
31        )?
32        .ok_or_else(|| create_error!(NotFound))
33    }
34
35    /// Fetch bots owned by a user
36    async fn fetch_bots_by_user(&self, user_id: &str) -> Result<Vec<Bot>> {
37        query!(
38            self,
39            find,
40            COL,
41            doc! {
42                "owner": user_id
43            }
44        )
45    }
46
47    /// Get the number of bots owned by a user
48    async fn get_number_of_bots_by_user(&self, user_id: &str) -> Result<usize> {
49        query!(
50            self,
51            count_documents,
52            COL,
53            doc! {
54                "owner": user_id
55            }
56        )
57        .map(|v| v as usize)
58    }
59
60    /// Update bot with new information
61    async fn update_bot(
62        &self,
63        id: &str,
64        partial: &PartialBot,
65        remove: Vec<FieldsBot>,
66    ) -> Result<()> {
67        query!(
68            self,
69            update_one_by_id,
70            COL,
71            id,
72            partial,
73            remove.iter().map(|x| x as &dyn IntoDocumentPath).collect(),
74            None
75        )
76        .map(|_| ())
77    }
78
79    /// Delete a bot from the database
80    async fn delete_bot(&self, id: &str) -> Result<()> {
81        query!(self, delete_one_by_id, COL, id).map(|_| ())
82    }
83}
84
85impl IntoDocumentPath for FieldsBot {
86    fn as_path(&self) -> Option<&'static str> {
87        match self {
88            FieldsBot::InteractionsURL => Some("interactions_url"),
89            FieldsBot::Token => None,
90        }
91    }
92}