|
| 1 | +use serde::Deserialize; |
| 2 | + |
| 3 | +#[derive(Deserialize)] |
| 4 | +pub(crate) struct Config { |
| 5 | + pub(crate) server_config: ServerConfig, |
| 6 | + pub(crate) postgresql_config: Option<PostgreSQLConfig>, |
| 7 | +} |
| 8 | + |
| 9 | +#[derive(Deserialize)] |
| 10 | +pub(crate) struct ServerConfig { |
| 11 | + pub(crate) host: String, |
| 12 | + pub(crate) port: u16, |
| 13 | +} |
| 14 | + |
| 15 | +#[derive(Deserialize)] |
| 16 | +pub(crate) struct PostgreSQLConfig { |
| 17 | + pub(crate) username: Option<String>, // Optional in TOML, can be overridden by env |
| 18 | + pub(crate) password: Option<String>, // Optional in TOML, can be overridden by env |
| 19 | + pub(crate) host: String, |
| 20 | + pub(crate) port: u16, |
| 21 | + pub(crate) database: String, |
| 22 | +} |
| 23 | + |
| 24 | +impl PostgreSQLConfig { |
| 25 | + pub(crate) fn to_connection_string(&self) -> String { |
| 26 | + let username_env = std::env::var("VSS_POSTGRESQL_USERNAME"); |
| 27 | + let username = username_env.as_ref() |
| 28 | + .ok() |
| 29 | + .or_else(|| self.username.as_ref()) |
| 30 | + .expect("PostgreSQL database username must be provided in config or env var VSS_POSTGRESQL_USERNAME must be set."); |
| 31 | + let password_env = std::env::var("VSS_POSTGRESQL_PASSWORD"); |
| 32 | + let password = password_env.as_ref() |
| 33 | + .ok() |
| 34 | + .or_else(|| self.password.as_ref()) |
| 35 | + .expect("PostgreSQL database password must be provided in config or env var VSS_POSTGRESQL_PASSWORD must be set."); |
| 36 | + |
| 37 | + format!( |
| 38 | + "postgresql://{}:{}@{}:{}/{}", |
| 39 | + username, password, self.host, self.port, self.database |
| 40 | + ) |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +pub(crate) fn load_config(config_path: &str) -> Result<Config, Box<dyn std::error::Error>> { |
| 45 | + let config_str = std::fs::read_to_string(config_path)?; |
| 46 | + let config: Config = toml::from_str(&config_str)?; |
| 47 | + Ok(config) |
| 48 | +} |
0 commit comments