opendal/services/mongodb/
config.rs1use std::fmt::Debug;
19
20use serde::Deserialize;
21use serde::Serialize;
22
23use super::backend::MongodbBuilder;
24
25#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
27#[serde(default)]
28#[non_exhaustive]
29pub struct MongodbConfig {
30 pub connection_string: Option<String>,
32 pub database: Option<String>,
34 pub collection: Option<String>,
36 pub root: Option<String>,
38 pub key_field: Option<String>,
40 pub value_field: Option<String>,
42}
43
44impl Debug for MongodbConfig {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 f.debug_struct("MongodbConfig")
47 .field("database", &self.database)
48 .field("collection", &self.collection)
49 .field("root", &self.root)
50 .field("key_field", &self.key_field)
51 .field("value_field", &self.value_field)
52 .finish_non_exhaustive()
53 }
54}
55
56impl crate::Configurator for MongodbConfig {
57 type Builder = MongodbBuilder;
58
59 fn from_uri(uri: &crate::types::OperatorUri) -> crate::Result<Self> {
60 let mut map = uri.options().clone();
61
62 if let Some(authority) = uri.authority() {
63 map.entry("connection_string".to_string())
64 .or_insert_with(|| format!("mongodb://{authority}"));
65 }
66
67 if let Some(path) = uri.root() {
68 if !path.is_empty() {
69 let mut segments = path.splitn(3, '/');
70 if let Some(db) = segments.next() {
71 if !db.is_empty() {
72 map.entry("database".to_string())
73 .or_insert_with(|| db.to_string());
74 }
75 }
76 if let Some(collection) = segments.next() {
77 if !collection.is_empty() {
78 map.entry("collection".to_string())
79 .or_insert_with(|| collection.to_string());
80 }
81 }
82 if let Some(rest) = segments.next() {
83 if !rest.is_empty() {
84 map.insert("root".to_string(), rest.to_string());
85 }
86 }
87 }
88 }
89
90 Self::from_iter(map)
91 }
92
93 fn into_builder(self) -> Self::Builder {
94 MongodbBuilder { config: self }
95 }
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101 use crate::Configurator;
102 use crate::types::OperatorUri;
103
104 #[test]
105 fn from_uri_sets_connection_string_database_collection_and_root() {
106 let uri = OperatorUri::new(
107 "mongodb://mongo.internal:27017/analytics/events/session",
108 Vec::<(String, String)>::new(),
109 )
110 .unwrap();
111
112 let cfg = MongodbConfig::from_uri(&uri).unwrap();
113 assert_eq!(
114 cfg.connection_string.as_deref(),
115 Some("mongodb://mongo.internal:27017")
116 );
117 assert_eq!(cfg.database.as_deref(), Some("analytics"));
118 assert_eq!(cfg.collection.as_deref(), Some("events"));
119 assert_eq!(cfg.root.as_deref(), Some("session"));
120 }
121}