refactor: reorganize settings into separate modules for improved structure and maintainability
This commit is contained in:
75
apps/nxmesh-master/src/config/settings/mod.rs
Normal file
75
apps/nxmesh-master/src/config/settings/mod.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
use config::{Config, ConfigError, Environment, File};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub type ValidationError = String;
|
||||
|
||||
pub mod auth;
|
||||
pub mod cert;
|
||||
pub mod cors;
|
||||
pub mod database;
|
||||
pub mod grpc;
|
||||
pub mod log;
|
||||
pub mod server;
|
||||
|
||||
use auth::AuthSettings;
|
||||
use database::DatabaseSettings;
|
||||
use grpc::GrpcSettings;
|
||||
use log::LogSettings;
|
||||
use server::ServerSettings;
|
||||
|
||||
pub trait Validate {
|
||||
fn validate(&self) -> Result<(), ValidationError>;
|
||||
}
|
||||
|
||||
/// Master server settings
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Settings {
|
||||
pub server: ServerSettings,
|
||||
pub database: DatabaseSettings,
|
||||
pub grpc: GrpcSettings,
|
||||
pub auth: AuthSettings,
|
||||
#[serde(default)]
|
||||
pub log: LogSettings,
|
||||
}
|
||||
|
||||
impl Validate for Settings {
|
||||
fn validate(&self) -> Result<(), ValidationError> {
|
||||
self.server.validate()?;
|
||||
self.grpc.validate()?;
|
||||
self.database.validate()?;
|
||||
self.auth.validate()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// Load settings from config files and environment
|
||||
pub fn load() -> Result<Self, ConfigError> {
|
||||
let run_mode = std::env::var("RUN_MODE").unwrap_or_else(|_| "development".into());
|
||||
|
||||
let settings = Config::builder()
|
||||
.add_source(File::with_name("config/default").required(false))
|
||||
.add_source(File::with_name(&format!("config/{}", run_mode)).required(false))
|
||||
.add_source(File::with_name("config/master/default").required(false))
|
||||
.add_source(File::with_name(&format!("config/master/{}", run_mode)).required(false))
|
||||
.add_source(Environment::with_prefix("NXMESH").separator("__"))
|
||||
.build()?;
|
||||
|
||||
let settings: Self = settings.try_deserialize()?;
|
||||
|
||||
settings.validate().map_err(ConfigError::Message)?;
|
||||
|
||||
Ok(settings)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_esnure_send_and_sync() {
|
||||
fn assert_send_sync<T: Send + Sync>() {}
|
||||
assert_send_sync::<Settings>();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user