Use once_cell
to keep the configuration
In order to keep the configuration globally available use `once_cell`. Also check for a valid email address in the part which is receiving the data from the api.
This commit is contained in:
parent
05e63acca5
commit
7ad6f610d1
6 changed files with 61 additions and 11 deletions
|
@ -1,4 +1,6 @@
|
|||
use anyhow::{bail, Error, Result};
|
||||
use anyhow::{anyhow, bail, Error, Result};
|
||||
use lettre::{message::Mailbox, Address};
|
||||
use once_cell::sync::OnceCell;
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
env, fs,
|
||||
|
@ -7,6 +9,8 @@ use std::{
|
|||
};
|
||||
use tracing::{error, info, trace, warn};
|
||||
|
||||
static CONFIG: OnceCell<Config> = OnceCell::new();
|
||||
|
||||
fn default_database_host() -> String {
|
||||
"localhost".to_string()
|
||||
}
|
||||
|
@ -75,15 +79,42 @@ impl Default for Server {
|
|||
}
|
||||
}
|
||||
|
||||
fn default_email_from() -> Mailbox {
|
||||
Mailbox::new(
|
||||
Some(env!("CARGO_BIN_NAME").to_string()),
|
||||
Address::new(env!("CARGO_BIN_NAME"), "localhost").unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Email {
|
||||
/// Address the notification emails are sent from
|
||||
#[serde(default = "default_email_from")]
|
||||
pub from: Mailbox,
|
||||
}
|
||||
|
||||
impl Default for Email {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
from: default_email_from(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Config {
|
||||
/// Database configuration
|
||||
pub database: Database,
|
||||
|
||||
/// server configuration
|
||||
/// Server configuration
|
||||
#[serde(default)]
|
||||
pub server: Server,
|
||||
|
||||
/// Email configuration
|
||||
#[serde(default)]
|
||||
pub email: Email,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
|
@ -130,4 +161,15 @@ impl Config {
|
|||
Ok(Self::try_paths()?)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(file: Option<PathBuf>) -> Result<()> {
|
||||
CONFIG
|
||||
.set(Self::load_config(file)?)
|
||||
.map_err(|_| anyhow!("configuration already initialized"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get() -> &'static Self {
|
||||
CONFIG.get().expect("config is not initialized")
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue