use nanoservices_utils::errors::{NanoServiceError, NanoServiceErrorStatus};
pub trait GetEnv {
fn get_env_var(key: &str) -> Result<String, NanoServiceError>;
}
pub struct EnviroVarConfig;
impl GetEnv for EnviroVarConfig {
fn get_env_var(key: &str) -> Result<String, NanoServiceError> {
match std::env::var(key) {
Ok(value) => Ok(value),
Err(e) => Err(NanoServiceError::new(e.to_string(), NanoServiceErrorStatus::NotFound)),
}
}
}
pub fn get_url<T: GetEnv>() -> String {
match T::get_env_var("URL") {
Ok(url) => url,
Err(_) => "127.0.0.1:8080".to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use nanoservices_utils::errors::NanoServiceErrorStatus;
#[test]
fn test_get_url() {
struct TestEnv;
impl GetEnv for TestEnv {
fn get_env_var(key: &str) -> Result<String, NanoServiceError> {
match key {
"URL" => Ok("test".to_string()),
_ => Err(NanoServiceError::new(
"not found".to_string(),
NanoServiceErrorStatus::NotFound,
)),
}
}
}
assert_eq!(get_url::<TestEnv>(), "test".to_string());
}
#[test]
fn test_get_url_fail() {
struct TestEnv;
impl GetEnv for TestEnv {
fn get_env_var(_: &str) -> Result<String, NanoServiceError> {
Err(NanoServiceError::new(
"not found".to_string(),
NanoServiceErrorStatus::NotFound,
))
}
}
assert_eq!(get_url::<TestEnv>(), "127.0.0.1:8080".to_string());
}
}