use serde::{Deserialize, Serialize};
use std::env;
use crate::error::Error::ConfigError;
const ENV_DB_HOST: &str = "DB_HOST";
const ENV_DB_NAME: &str = "DB_NAME";
const ENV_DB_PASSWORD: &str = "DB_PASSWORD";
const ENV_DB_PORT: &str = "DB_PORT";
const ENV_DB_USER: &str = "DB_USER";
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DatabaseConfig {
pub host: String,
pub name: String,
pub password: String,
pub port: i32,
pub user: String,
}
impl Default for DatabaseConfig {
fn default() -> Self {
DatabaseConfig {
host: String::from("localhost"),
name: String::from("postgres"),
password: String::from("postgres"),
port: 5432,
user: String::from("postgres"),
}
}
}
impl DatabaseConfig {
pub fn from_env() -> Result<Self, crate::error::Error> {
let env_host = match env::var(ENV_DB_HOST) {
Ok(value) => value,
Err(e) => return Err(ConfigError(e.to_string())),
};
let env_name = match env::var(ENV_DB_NAME) {
Ok(value) => value,
Err(e) => return Err(ConfigError(e.to_string())),
};
let env_pw = match env::var(ENV_DB_PASSWORD) {
Ok(value) => value,
Err(e) => return Err(ConfigError(e.to_string())),
};
let env_port = match env::var(ENV_DB_PORT) {
Ok(value) => match value.parse::<i32>() {
Ok(int_value) => int_value,
Err(e) => return Err(ConfigError(e.to_string())),
},
Err(e) => return Err(ConfigError(e.to_string())),
};
let env_user = match env::var(ENV_DB_USER) {
Ok(value) => value,
Err(e) => return Err(ConfigError(e.to_string())),
};
Ok(Self {
host: env_host,
name: env_name,
password: env_pw,
port: env_port,
user: env_user,
})
} }