nanoservices_utils/config.rs
1//! Defines extracting config variables based on the method to enable testing as well as production use.
2//! A good is API views. Wehn when defining an API view function, we can use the `GetConfigVariable` trait to
3//! to enable config variables from different sources be applied to the API view function by having the following
4//! outline:
5//!
6//! ```rust
7//! use nanoservices_utils::config::GetConfigVariable;
8//!
9//! pub async fn api_view<T: GetConfigVariable>() {
10//! }
11//! ```
12//! Anything passed into the `api_view` function will be able to get config variables from the source defined by
13//! the type of the generic parameter `T`. For example, if we want to get config variables from the environment, we
14//! can pass the `EnvConfig` struct as `api_view::<EnvConfig>()`. However, we can implement the `GetConfigVariable`
15//! on a random struct for unit testing and pass that struct into the `api_view` function for testing.
16//! use nanoservices_utils::config::GetConfigVariable;
17//!
18//! let _ =
19use std::env;
20use crate::errors::{
21 NanoServiceError,
22 NanoServiceErrorStatus
23};
24
25
26/// Used for extracting config cariables.
27pub trait GetConfigVariable {
28
29 /// Gets the config variable
30 ///
31 /// # Arguments
32 /// * `variable` - The name of the config variable to get
33 ///
34 /// # Returns
35 /// * `Result<String, NanoServiceError>` - The result of getting the config variable
36 fn get_config_variable(variable: String) -> Result<String, NanoServiceError>;
37}
38
39
40/// Defines the struct for getting config variables from the environment
41pub struct EnvConfig;
42
43impl GetConfigVariable for EnvConfig {
44
45 /// Gets the config variable from the environment
46 ///
47 /// # Arguments
48 /// * `variable` - The name of the config variable to get
49 ///
50 /// # Returns
51 /// * `Result<String, NanoServiceError>` - The result of getting the config variable
52 fn get_config_variable(variable: String) -> Result<String, NanoServiceError> {
53 match env::var(&variable) {
54 Ok(val) => Ok(val),
55 Err(_) => Err(
56 NanoServiceError::new(
57 format!("{} not found in environment", variable),
58 NanoServiceErrorStatus::Unknown
59 )
60 )
61 }
62 }
63}