Skip to content

Commit

Permalink
feat(config)!: allow configuring database name (#240)
Browse files Browse the repository at this point in the history
* Allow configuring entire database name
  • Loading branch information
Alexandcoats authored and grtlr committed Jun 10, 2022
1 parent d7d1643 commit e13fe42
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 11 deletions.
1 change: 1 addition & 0 deletions bin/inx-chronicle/config.template.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
connect_url = "mongodb://localhost:27017"
username = "root"
password = "root"
database_name = "chronicle"

[api]
port = 8042
Expand Down
16 changes: 6 additions & 10 deletions src/db/mongodb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use serde::{Deserialize, Serialize};
pub struct MongoDb(pub(crate) mongodb::Database);

impl MongoDb {
const NAME: &'static str = "chronicle";
const DEFAULT_NAME: &'static str = "chronicle";
const DEFAULT_CONNECT_URL: &'static str = "mongodb://localhost:27017";

/// Constructs a [`MongoDb`] by connecting to a MongoDB instance.
Expand All @@ -35,11 +35,7 @@ impl MongoDb {

let client = Client::with_options(client_options)?;

let name = match &config.suffix {
Some(suffix) => format!("{}-{}", Self::NAME, suffix),
None => Self::NAME.to_string(),
};
let db = client.database(&name);
let db = client.database(&config.database_name);

Ok(MongoDb(db))
}
Expand Down Expand Up @@ -83,7 +79,7 @@ pub struct MongoDbConfig {
pub(crate) connect_url: String,
pub(crate) username: Option<String>,
pub(crate) password: Option<String>,
pub(crate) suffix: Option<String>,
pub(crate) database_name: String,
}

impl MongoDbConfig {
Expand Down Expand Up @@ -111,8 +107,8 @@ impl MongoDbConfig {
}

/// Sets the suffix.
pub fn with_suffix(mut self, suffix: impl Into<String>) -> Self {
self.suffix = Some(suffix.into());
pub fn with_database_name(mut self, database_name: impl Into<String>) -> Self {
self.database_name = database_name.into();
self
}
}
Expand All @@ -123,7 +119,7 @@ impl Default for MongoDbConfig {
connect_url: MongoDb::DEFAULT_CONNECT_URL.to_string(),
username: None,
password: None,
suffix: None,
database_name: MongoDb::DEFAULT_NAME.to_string(),
}
}
}
2 changes: 1 addition & 1 deletion tests/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async fn insert_and_get_block() -> Result<(), mongodb::error::Error> {
conflict_reason: ConflictReason::None,
};

let config = MongoDbConfig::default().with_suffix("cargo-test");
let config = MongoDbConfig::default().with_database_name("chronicle-cargo-test");
let db = MongoDb::connect(&config).await?;

db.clear().await?;
Expand Down

0 comments on commit e13fe42

Please sign in to comment.