surrealcs 0.4.4

The SurrealCS client code for SurrealDB
Documentation
//! Utils around getting environment variables.
use nanoservices_utils::errors::{NanoServiceError, NanoServiceErrorStatus};

/// For getting an environment variable.
pub trait GetEnv {
	fn get_env_var(key: &str) -> Result<String, NanoServiceError>;
}

/// The default implementation for getting an environment variable.
pub struct EnviroVarConfig;

impl GetEnv for EnviroVarConfig {
	/// Gets an environment variable.
	///
	/// # Arguments
	/// * `key`: the key of the environment variable
	///
	/// # Returns
	/// The value of the environment variable or an error if it is not found
	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)),
		}
	}
}

/// Gets the URL for the server based on the `URL` environment variable
///
/// # Returns
/// The URL or `127.0.0.1:8080` if the `"URL"` environment variable is not defined
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());
	}
}