Skip to main content

fusion_core/configuration/model/
app_setting.rs

1use fusion_common::time::{DateTime, FixedOffset, Local, deser::deserialize_fixed_offset, ser::serialize_fixed_offset};
2use serde::{Deserialize, Serialize};
3
4use crate::RunMode;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct AppSetting {
8  run_mode: RunMode,
9
10  /// 应用名称。通常用于服务注册、日志打印等
11  name: String,
12
13  /// 系统使用时区,默认为 +08:00
14  #[serde(serialize_with = "serialize_fixed_offset", deserialize_with = "deserialize_fixed_offset")]
15  time_offset: FixedOffset,
16}
17
18impl AppSetting {
19  pub fn run_mode(&self) -> &RunMode {
20    &self.run_mode
21  }
22
23  pub fn name(&self) -> &str {
24    &self.name
25  }
26
27  pub fn time_offset(&self) -> &FixedOffset {
28    &self.time_offset
29  }
30
31  pub fn time_now(&self) -> DateTime<FixedOffset> {
32    Local::now().with_timezone(self.time_offset())
33  }
34}
35
36#[cfg(test)]
37mod tests {
38  use config::{Config, File, FileFormat};
39  use fusion_common::time::FixedOffset;
40
41  use crate::RunMode;
42
43  use super::AppSetting;
44
45  #[test]
46  fn test_app_conf() {
47    let text = r#"
48      run_mode = "dev"
49      name = "fusion"
50      time_offset = "+08:00"
51    "#;
52    let s = File::from_str(text, FileFormat::Toml);
53    let c = Config::builder().add_source(s).build().unwrap();
54    let app: AppSetting = c.try_deserialize().unwrap();
55    println!("{:?}", app);
56    assert_eq!(app.run_mode(), &RunMode::DEV);
57    assert_eq!(app.time_offset(), &FixedOffset::east_opt(8 * 3600).unwrap());
58  }
59}