1use poem::middleware::Cors;
13
14pub const PUERTO_POR_DEFECTO: u16 = 8080;
16
17#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
19#[non_exhaustive]
20pub enum ErrorConfig {
21 #[error("{clave}={valor:?} no es válida: se esperaba {esperado}")]
22 Invalido {
23 clave: &'static str,
24 valor: String,
25 esperado: &'static str,
26 },
27}
28
29pub fn cargar_dotenv() {
31 dotenvy::dotenv().ok();
32}
33
34#[derive(Debug, Clone)]
36#[non_exhaustive]
37pub struct Config {
38 puerto: u16,
39 origenes_cors_permitidos: Vec<String>,
40 banner: bool,
41}
42
43impl Default for Config {
44 fn default() -> Self {
45 Self {
46 puerto: PUERTO_POR_DEFECTO,
47 origenes_cors_permitidos: vec![],
48 banner: true,
49 }
50 }
51}
52
53impl Config {
54 pub fn from_env() -> Result<Self, ErrorConfig> {
56 cargar_dotenv();
57 Self::from_variables(|clave| std::env::var(clave).ok())
58 }
59
60 pub fn from_variables(var: impl Fn(&str) -> Option<String>) -> Result<Self, ErrorConfig> {
62 let var = |clave: &str| var(clave).filter(|valor| !valor.trim().is_empty());
63 let mut config = Self::default();
64 if let Some(valor) = var("SERVICE_PORT") {
65 config.puerto = valor.trim().parse().map_err(|_| ErrorConfig::Invalido {
66 clave: "SERVICE_PORT",
67 valor,
68 esperado: "un número de puerto (0-65535)",
69 })?;
70 }
71 if let Some(valor) = var("CORS_ALLOWED_ORIGINS") {
72 config.origenes_cors_permitidos = valor
73 .split(',')
74 .map(str::trim)
75 .filter(|origin| !origin.is_empty())
76 .map(String::from)
77 .collect();
78 }
79 if let Some(valor) = var("PUERTO_BANNER") {
80 config.banner = match valor.trim() {
81 "true" | "1" => true,
82 "false" | "0" => false,
83 _ => {
84 return Err(ErrorConfig::Invalido {
85 clave: "PUERTO_BANNER",
86 valor,
87 esperado: "true o false",
88 });
89 }
90 };
91 }
92 Ok(config)
93 }
94
95 pub fn con_puerto(mut self, puerto: u16) -> Self {
96 self.puerto = puerto;
97 self
98 }
99
100 pub fn con_origenes_cors_permitidos(mut self, origins: Vec<String>) -> Self {
101 self.origenes_cors_permitidos = origins;
102 self
103 }
104
105 pub fn con_banner(mut self, banner: bool) -> Self {
106 self.banner = banner;
107 self
108 }
109
110 pub fn puerto(&self) -> u16 {
111 self.puerto
112 }
113
114 pub fn origenes_cors_permitidos(&self) -> &[String] {
115 &self.origenes_cors_permitidos
116 }
117
118 pub fn banner(&self) -> bool {
119 self.banner
120 }
121
122 pub fn cors(&self) -> Cors {
124 self.origenes_cors_permitidos
125 .iter()
126 .fold(Cors::new(), |cors, origin| {
127 cors.allow_origin(origin.as_str())
128 })
129 }
130}
131
132#[cfg(test)]
133mod tests {
134 use super::*;
135
136 fn vars(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
137 let pairs: Vec<(String, String)> = pairs
138 .iter()
139 .map(|(k, v)| (k.to_string(), v.to_string()))
140 .collect();
141 move |clave| {
142 pairs
143 .iter()
144 .find(|(k, _)| k == clave)
145 .map(|(_, v)| v.clone())
146 }
147 }
148
149 #[test]
150 fn should_use_the_defaults_when_nothing_is_set() {
151 let config = Config::from_variables(vars(&[])).unwrap();
153
154 assert_eq!(config.puerto(), 8080);
156 assert!(config.origenes_cors_permitidos().is_empty());
157 assert!(config.banner());
158 }
159
160 #[test]
161 fn should_read_every_variable_when_set() {
162 let config = Config::from_variables(vars(&[
164 ("SERVICE_PORT", "3000"),
165 (
166 "CORS_ALLOWED_ORIGINS",
167 "http://localhost:5173, https://app.example.com,",
168 ),
169 ("PUERTO_BANNER", "false"),
170 ]))
171 .unwrap();
172
173 assert_eq!(config.puerto(), 3000);
175 assert_eq!(
176 config.origenes_cors_permitidos(),
177 ["http://localhost:5173", "https://app.example.com"]
178 );
179 assert!(!config.banner());
180 }
181
182 #[test]
183 fn should_reject_the_port_when_it_is_not_a_number() {
184 let result = Config::from_variables(vars(&[("SERVICE_PORT", "abc")]));
186
187 assert_eq!(
189 result.unwrap_err(),
190 ErrorConfig::Invalido {
191 clave: "SERVICE_PORT",
192 valor: "abc".into(),
193 esperado: "un número de puerto (0-65535)",
194 }
195 );
196 }
197
198 #[test]
199 fn should_reject_the_port_when_it_is_out_of_range() {
200 let result = Config::from_variables(vars(&[("SERVICE_PORT", "70000")]));
202
203 assert!(result.is_err());
205 }
206
207 #[test]
208 fn should_reject_the_banner_when_it_is_not_a_boolean() {
209 let result = Config::from_variables(vars(&[("PUERTO_BANNER", "no")]));
211
212 assert!(matches!(
214 result,
215 Err(ErrorConfig::Invalido {
216 clave: "PUERTO_BANNER",
217 ..
218 })
219 ));
220 }
221
222 #[test]
223 fn should_show_the_banner_when_it_is_switched_on() {
224 for on in ["true", "1"] {
225 let config = Config::from_variables(vars(&[("PUERTO_BANNER", on)])).unwrap();
227
228 assert!(config.banner(), "{on}");
230 }
231 }
232
233 #[test]
234 fn should_override_the_defaults_when_built_by_hand() {
235 let config = Config::default()
237 .con_puerto(3000)
238 .con_banner(false)
239 .con_origenes_cors_permitidos(vec!["http://localhost:5173".into()]);
240
241 assert_eq!(config.puerto(), 3000);
243 assert!(!config.banner());
244 assert_eq!(config.origenes_cors_permitidos(), ["http://localhost:5173"]);
245 }
246
247 #[test]
248 fn should_treat_an_empty_value_as_unset() {
249 let config =
251 Config::from_variables(vars(&[("SERVICE_PORT", ""), ("PUERTO_BANNER", "")])).unwrap();
252
253 assert_eq!(config.puerto(), PUERTO_POR_DEFECTO);
255 assert!(config.banner());
256 }
257
258 #[test]
259 fn should_say_which_variable_is_wrong() {
260 let mensaje = Config::from_variables(vars(&[("SERVICE_PORT", "abc")]))
262 .unwrap_err()
263 .to_string();
264
265 assert_eq!(
267 mensaje,
268 "SERVICE_PORT=\"abc\" no es válida: se esperaba un número de puerto (0-65535)"
269 );
270 }
271}