pillow_env/
lib.rs

1//! Eviroment Variables
2//!
3//! Get variables from .env file
4
5use dotenv::dotenv;
6use std::{collections::HashMap, env};
7
8/// Eviroment variables implementation
9#[derive(Debug)]
10pub struct Env {
11    pub variables: HashMap<String, String>,
12}
13
14impl Env {
15    /// Create a new Env with all variables in .env file
16    pub fn new() -> Env {
17        dotenv().ok();
18
19        let mut variables: HashMap<String, String> = HashMap::new();
20
21        for (k, v) in env::vars() {
22            variables.insert(k, v);
23        }
24
25        Env { variables }
26    }
27}
28
29impl Env {
30    /// Returns String value from .env
31    ///
32    /// # Arguments
33    ///
34    /// * `var` - name of variable
35    ///
36    /// # Examples
37    ///
38    /// ```rust
39    /// use pillow::env::Env
40    ///
41    /// let port = Env::get_env_var("".to_string());
42    /// ```
43    pub fn get_env_var(var: String) -> String {
44        dotenv().ok();
45
46        match env::var(&var) {
47            Ok(v) => v,
48            Err(error) => panic!("${var} is not set: {error}"),
49        }
50    }
51
52    /// Returns Bool if env var exists
53    ///
54    ///  # Arguments
55    ///
56    ///  * `var` - name of variable
57    ///
58    ///  # Examples
59    ///
60    ///  ```rust
61    ///  use pillow::env::Env
62    ///
63    ///  if (Env::is_var_exist("var".to_string())){}
64    ///  ```
65    pub fn is_var_exist(var: String) -> bool {
66        dotenv().ok();
67
68        match env::var(var) {
69            Ok(_) => true,
70            Err(_) => false,
71        }
72    }
73
74    /// Returns variable if exists
75    pub fn var_exists(var: String) -> Option<String> {
76        dotenv().ok();
77
78        if Self::is_var_exist(var.to_string()) {
79            Some(Self::get_env_var(var))
80        } else {
81            None
82        }
83    }
84}