revolt_database/models/user_settings/ops/
mongodb.rs

1use ::mongodb::options::FindOneOptions;
2use bson::to_bson;
3use bson::Document;
4use mongodb::options::UpdateOptions;
5use revolt_result::Result;
6
7use crate::MongoDb;
8use crate::UserSettings;
9
10use super::AbstractUserSettings;
11
12static COL: &str = "user_settings";
13
14#[async_trait]
15impl AbstractUserSettings for MongoDb {
16    /// Fetch a subset of user settings
17    async fn fetch_user_settings(&'_ self, id: &str, filter: &'_ [String]) -> Result<UserSettings> {
18        let mut projection = doc! {
19            "_id": 0,
20        };
21
22        for key in filter {
23            projection.insert(key, 1);
24        }
25
26        Ok(query!(
27            self,
28            find_one_with_options,
29            COL,
30            doc! {
31                "_id": id
32            },
33            FindOneOptions::builder().projection(projection).build()
34        )?
35        .unwrap_or_default())
36    }
37
38    /// Update a subset of user settings
39    async fn set_user_settings(&self, id: &str, settings: &UserSettings) -> Result<()> {
40        let mut set = doc! {};
41        for (key, data) in settings {
42            set.insert(
43                key,
44                vec![to_bson(&data.0).unwrap(), to_bson(&data.1).unwrap()],
45            );
46        }
47
48        self.col::<Document>(COL)
49            .update_one(
50                doc! {
51                    "_id": id
52                },
53                doc! {
54                    "$set": set
55                },
56            )
57            .with_options(UpdateOptions::builder().upsert(true).build())
58            .await
59            .map(|_| ())
60            .map_err(|_| create_database_error!("update_one", "user_settings"))
61    }
62
63    /// Delete all user settings
64    async fn delete_user_settings(&self, id: &str) -> Result<()> {
65        query!(self, delete_one_by_id, COL, id).map(|_| ())
66    }
67}