shared/infrastructure/database/mongodb/
repository.rs1use super::MongodbIndexes;
2use crate::error::{CoreError, InternalError};
3
4const NO_CLIENT: &str = "No available server found for connection string '{}'. Please verify that the connection string is valid and the server is reachable.";
5const NO_DB: &str = "Failed to get default database: MongoDB client has no default database configured. Ensure 'default_database' is set in the connection string or client options.";
6
7pub struct MongoDB {}
8impl MongoDB {
9 pub async fn start(connection_string: &str) -> Result<mongodb::Client, CoreError> {
10 let client = mongodb::Client::with_uri_str(&connection_string)
11 .await
12 .map_err(|e| {
13 tracing::error!(
14 error_code = "InternalError::Database",
15 "Failed to connect to database - {e}"
16 );
17 CoreError::Internal(InternalError::Database(
18 NO_CLIENT.replace("{}", connection_string),
19 ))
20 })?;
21
22 let db = client
23 .default_database()
24 .ok_or_else(|| CoreError::Internal(InternalError::Database(NO_DB.into())))?;
25
26 let mongodb_indexes = MongodbIndexes { db: db.clone() };
27 mongodb_indexes
28 .create_unique_email_index()
29 .await
30 .inspect_err(|e| {
31 tracing::error!(
32 error_code = "InternalError::Database",
33 "Failed to create index for email attribute in users Collection - {e}"
34 );
35 })?;
36
37 mongodb_indexes
38 .create_token_hash_index()
39 .await
40 .inspect_err(|e| {
41 tracing::error!(
42 error_code = "InternalError::Database",
43 "Failed to create index for email attribute in password_reset_tokens Collection - {e}"
44 );
45 })?;
46
47 mongodb_indexes
48 .create_role_permission_index()
49 .await
50 .inspect_err(|e| {
51 tracing::error!(
52 error_code = "InternalError::Database",
53 "Failed to create index for roleId+permissionId attribute in role_permissions Collection - {e}"
54 );
55 })?;
56
57 mongodb_indexes
58 .create_user_role_index()
59 .await
60 .inspect_err(|e| {
61 tracing::error!(
62 error_code = "InternalError::Database",
63 "Failed to create index for roleId+userId attribute in user_roles Collection - {e}"
64 );
65 })?;
66
67 Ok(client)
68 }
69}