nishantcoder108 commited on
Commit
c19a362
·
1 Parent(s): f977699

feat: implement configuration for importing env variable in project

Browse files
Files changed (1) hide show
  1. src/config.rs +48 -0
src/config.rs ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::{env, net::SocketAddr};
2
+
3
+ use crate::errors::{AppError, AppResult};
4
+
5
+ #[derive(Clone, Debug)]
6
+ pub struct AppConfig {
7
+ pub database_url: String,
8
+ pub jwt_secret: String,
9
+ pub frontend_origin: String,
10
+ pub address: SocketAddr,
11
+ pub cookie_secure: bool,
12
+ }
13
+
14
+ impl AppConfig {
15
+ pub fn from_env() -> AppResult<Self> {
16
+ let database_url = env::var("DATABASE_URL")
17
+ .map_err(|_| AppError::Config("DATABASE_URL is required".to_owned()))?;
18
+ let jwt_secret = env::var("JWT_SECRET")
19
+ .map_err(|_| AppError::Config("JWT_SECRET is required".to_owned()))?;
20
+ let frontend_origin =
21
+ env::var("FRONTEND_ORIGIN").unwrap_or_else(|_| "http://localhost:5173".to_owned());
22
+ let port = env::var("PORT")
23
+ .ok()
24
+ .and_then(|value| value.parse::<u16>().ok())
25
+ .unwrap_or(8080);
26
+ let host = env::var("HOST").unwrap_or_else(|_| "0.0.0.0".to_owned());
27
+ let cookie_secure = env::var("COOKIE_SECURE")
28
+ .ok()
29
+ .map(|value| matches!(value.as_str(), "1" | "true" | "TRUE" | "True"))
30
+ .unwrap_or_else(|| {
31
+ env::var("APP_ENV")
32
+ .map(|value| value.eq_ignore_ascii_case("production"))
33
+ .unwrap_or(false)
34
+ });
35
+
36
+ let address = format!("{host}:{port}")
37
+ .parse()
38
+ .map_err(|error| AppError::Config(format!("Invalid HOST/PORT combination: {error}")))?;
39
+
40
+ Ok(Self {
41
+ database_url,
42
+ jwt_secret,
43
+ frontend_origin,
44
+ address,
45
+ cookie_secure,
46
+ })
47
+ }
48
+ }